зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1481961: Revendor Rust dependencies. r=me
This commit is contained in:
Родитель
03eea217a8
Коммит
30c2ae52a8
|
@ -0,0 +1 @@
|
|||
{"files":{".travis.yml":"01adbc19d48f67683d067193dd2138f71de1d075292d438d4a980a018f8aa02f","Cargo.toml":"57dcf7e06d8a81aba6d207476e9d98b67ae1c626b42455d560ff4722bce331e9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"5c81631711af54d31e40841cd0153a95d9e505d8eba7503d114789ffb5e232c6","RELEASES.md":"ddb394449b049aace6f20cab3d6ab1de0c82f100a0c778e9790817c544590df5","bors.toml":"1c81ede536a37edd30fe4e622ff0531b25372403ac9475a5d6c50f14156565a2","ci/rustup.sh":"8f58c563be0c200447d528c3b9db296db16ce198e26e872aee210174d4daf518","ci/test_full.sh":"aa3c9fd125f4befddbd109698a0bb3e078e37c092e3fd52029aadb036bd58d3f","src/lib.rs":"9e525516c4bdca62c486fe8d0ef5960e35ec2d7b49a8f2b7e12b9e0383909191","tests/empty_enum.rs":"1b2312ec2fc9866fce7172e71e0aa2efcc3cb9d7659d0b633eb352bb1e080d53","tests/issue-6.rs":"e8eaa07255f00d420eeb5fb64ebd872ba58235d1af6b1f806a6784e6de316459","tests/issue-9.rs":"f64454c4411b73f9257974caeb4561ccf7850d097d0b0177d841c88bb05eaa02","tests/num_derive_without_num.rs":"3ce528221a2cb752859e20c5423c4b474fec714b41d8c1b62f5614b165d7262b","tests/trivial.rs":"31eac2d8c99e3846cca072015e255c72fea4f80a6f5f235f9c7fd76e122656ce","tests/with_custom_values.rs":"3d692c9c5d570ccb2b8d79ce848812bd72fe01db6f564beedcc69176900ca804"},"package":"0d2c31b75c36a993d30c7a13d70513cb93f02acafdd5b7ba250f9b0e18615de7"}
|
|
@ -0,0 +1,23 @@
|
|||
language: rust
|
||||
rust:
|
||||
- 1.15.0
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
env:
|
||||
matrix:
|
||||
- # no features
|
||||
- FEATURES="full-syntax"
|
||||
sudo: false
|
||||
script:
|
||||
- cargo build --verbose --features="$FEATURES"
|
||||
- ./ci/test_full.sh
|
||||
notifications:
|
||||
email:
|
||||
on_success: never
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- next
|
||||
- staging
|
||||
- trying
|
|
@ -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 = "num-derive"
|
||||
version = "0.2.2"
|
||||
authors = ["The Rust Project Developers"]
|
||||
description = "Numeric syntax extensions"
|
||||
homepage = "https://github.com/rust-num/num-derive"
|
||||
documentation = "https://docs.rs/num-derive"
|
||||
readme = "README.md"
|
||||
keywords = ["mathematics", "numerics"]
|
||||
categories = ["science"]
|
||||
license = "MIT/Apache-2.0"
|
||||
repository = "https://github.com/rust-num/num-derive"
|
||||
|
||||
[lib]
|
||||
name = "num_derive"
|
||||
test = false
|
||||
proc-macro = true
|
||||
[dependencies.num-traits]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.proc-macro2]
|
||||
version = "0.4.2"
|
||||
|
||||
[dependencies.quote]
|
||||
version = "0.6"
|
||||
|
||||
[dependencies.syn]
|
||||
version = "0.14"
|
||||
[dev-dependencies.num]
|
||||
version = "0.1"
|
||||
|
||||
[features]
|
||||
full-syntax = ["syn/full"]
|
|
@ -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.
|
|
@ -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.
|
|
@ -0,0 +1,53 @@
|
|||
# num-derive
|
||||
|
||||
[![crate](https://img.shields.io/crates/v/num-derive.svg)](https://crates.io/crates/num-derive)
|
||||
[![documentation](https://docs.rs/num-derive/badge.svg)](https://docs.rs/num-derive)
|
||||
[![Travis status](https://travis-ci.org/rust-num/num-derive.svg?branch=master)](https://travis-ci.org/rust-num/num-derive)
|
||||
|
||||
Procedural macros to derive numeric traits in Rust.
|
||||
|
||||
## Usage
|
||||
|
||||
Add this to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
num-traits = "0.2"
|
||||
num-derive = "0.2"
|
||||
```
|
||||
|
||||
and this to your crate root:
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
```
|
||||
|
||||
Then you can derive traits on your own types:
|
||||
|
||||
```rust
|
||||
#[derive(FromPrimitive, ToPrimitive)]
|
||||
enum Color {
|
||||
Red,
|
||||
Blue,
|
||||
Green,
|
||||
}
|
||||
```
|
||||
|
||||
## Optional features
|
||||
|
||||
- **`full-syntax`** — Enables `num-derive` to handle enum discriminants
|
||||
represented by complex expressions. Usually can be avoided by
|
||||
[utilizing constants], so only use this feature if namespace pollution is
|
||||
undesired and [compile time doubling] is acceptable.
|
||||
|
||||
[utilizing constants]: https://github.com/rust-num/num-derive/pull/3#issuecomment-359044704
|
||||
[compile time doubling]: https://github.com/rust-num/num-derive/pull/3#issuecomment-359172588
|
||||
|
||||
## Releases
|
||||
|
||||
Release notes are available in [RELEASES.md](RELEASES.md).
|
||||
|
||||
## Compatibility
|
||||
|
||||
The `num-derive` crate is tested for rustc 1.15 and greater.
|
|
@ -0,0 +1,58 @@
|
|||
# Release 0.2.2
|
||||
|
||||
- [Updated dependencies][14].
|
||||
|
||||
[14]: https://github.com/rust-num/num-derive/pull/14
|
||||
|
||||
# Release 0.2.1
|
||||
|
||||
- [Updated dependencies][12] -- thanks @spearman!
|
||||
|
||||
[12]: https://github.com/rust-num/num-derive/pull/12
|
||||
|
||||
# Release 0.2.0
|
||||
|
||||
- [Discriminant matching is now simplified][10], casting values directly by
|
||||
name, rather than trying to compute offsets from known values manually.
|
||||
- **breaking change**: [Derivations now import the traits from `num-traits`][11]
|
||||
instead of the full `num` crate. These are still compatible, but users need
|
||||
to have an explicit `num-traits = "0.2"` dependency in their `Cargo.toml`.
|
||||
|
||||
[10]: https://github.com/rust-num/num-derive/pull/10
|
||||
[11]: https://github.com/rust-num/num-derive/pull/11
|
||||
|
||||
|
||||
# Release 0.1.44
|
||||
|
||||
- [The derived code now explicitly allows `unused_qualifications`][9], so users
|
||||
that globally deny that lint don't encounter an error.
|
||||
|
||||
[9]: https://github.com/rust-num/num-derive/pull/9
|
||||
|
||||
|
||||
# Release 0.1.43
|
||||
|
||||
- [The derived code now explicitly allows `trivial_numeric_casts`][7], so users
|
||||
that globally deny that lint don't encounter an error.
|
||||
|
||||
[7]: https://github.com/rust-num/num-derive/pull/7
|
||||
|
||||
|
||||
# Release 0.1.42
|
||||
|
||||
- [num-derive now has its own source repository][num-356] at [rust-num/num-derive][home].
|
||||
- [The derivation macros have been updated][3] to using `syn` 0.12. Support for complex
|
||||
expressions in enum values can be enabled with the `full-syntax` feature.
|
||||
|
||||
Thanks to @cuviper and @hcpl for their contributions!
|
||||
|
||||
[home]: https://github.com/rust-num/num-derive
|
||||
[num-356]: https://github.com/rust-num/num/pull/356
|
||||
[3]: https://github.com/rust-num/num-derive/pull/3
|
||||
|
||||
|
||||
# Prior releases
|
||||
|
||||
No prior release notes were kept. Thanks all the same to the many
|
||||
contributors that have made this crate what it is!
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
status = [
|
||||
"continuous-integration/travis-ci/push",
|
||||
]
|
|
@ -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.15.0, stable, beta, and nightly.)
|
||||
|
||||
set -ex
|
||||
|
||||
export TRAVIS_RUST_VERSION
|
||||
for TRAVIS_RUST_VERSION in 1.15.0 stable beta nightly; do
|
||||
run="rustup run $TRAVIS_RUST_VERSION"
|
||||
$run cargo build --verbose
|
||||
$run $PWD/ci/test_full.sh
|
||||
done
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
echo Testing num-derive on rustc ${TRAVIS_RUST_VERSION}
|
||||
|
||||
# num-derive should build and test everywhere.
|
||||
cargo build --verbose --features="$FEATURES"
|
||||
cargo test --verbose --features="$FEATURES"
|
|
@ -0,0 +1,266 @@
|
|||
// 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.
|
||||
|
||||
#![crate_type = "proc-macro"]
|
||||
#![doc(html_root_url = "https://docs.rs/num-derive/0.2")]
|
||||
|
||||
//! Procedural macros to derive numeric traits in Rust.
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! Add this to your `Cargo.toml`:
|
||||
//!
|
||||
//! ```toml
|
||||
//! [dependencies]
|
||||
//! num-traits = "0.2"
|
||||
//! num-derive = "0.2"
|
||||
//! ```
|
||||
//!
|
||||
//! Then you can derive traits on your own types:
|
||||
//!
|
||||
//! ```rust
|
||||
//! #[macro_use]
|
||||
//! extern crate num_derive;
|
||||
//!
|
||||
//! #[derive(FromPrimitive, ToPrimitive)]
|
||||
//! enum Color {
|
||||
//! Red,
|
||||
//! Blue,
|
||||
//! Green,
|
||||
//! }
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
|
||||
extern crate proc_macro;
|
||||
|
||||
extern crate proc_macro2;
|
||||
#[macro_use]
|
||||
extern crate quote;
|
||||
extern crate syn;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Span;
|
||||
|
||||
use syn::{Data, Fields, Ident};
|
||||
|
||||
/// Derives [`num_traits::FromPrimitive`][from] for simple enums.
|
||||
///
|
||||
/// [from]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.FromPrimitive.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Simple enums can be derived:
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
///
|
||||
/// #[derive(FromPrimitive)]
|
||||
/// enum Color {
|
||||
/// Red,
|
||||
/// Blue,
|
||||
/// Green = 42,
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// Enums that contain data are not allowed:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
///
|
||||
/// #[derive(FromPrimitive)]
|
||||
/// enum Color {
|
||||
/// Rgb(u8, u8, u8),
|
||||
/// Hsv(u8, u8, u8),
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// Structs are not allowed:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
/// #[derive(FromPrimitive)]
|
||||
/// struct Color {
|
||||
/// r: u8,
|
||||
/// g: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro_derive(FromPrimitive)]
|
||||
pub fn from_primitive(input: TokenStream) -> TokenStream {
|
||||
let ast: syn::DeriveInput = syn::parse(input).unwrap();
|
||||
let name = &ast.ident;
|
||||
let dummy_const = Ident::new(&format!("_IMPL_NUM_FROM_PRIMITIVE_FOR_{}", name), Span::call_site());
|
||||
|
||||
let variants = match ast.data {
|
||||
Data::Enum(ref data_enum) => &data_enum.variants,
|
||||
_ => panic!("`FromPrimitive` can be applied only to the enums, {} is not an enum", name)
|
||||
};
|
||||
|
||||
let from_i64_var = quote! { n };
|
||||
let clauses: Vec<_> = variants.iter()
|
||||
.map(|variant| {
|
||||
let ident = &variant.ident;
|
||||
match variant.fields {
|
||||
Fields::Unit => (),
|
||||
_ => {
|
||||
panic!("`FromPrimitive` can be applied only to unitary enums, {}::{} is either struct or tuple", name, ident)
|
||||
},
|
||||
}
|
||||
|
||||
quote! {
|
||||
if #from_i64_var == #name::#ident as i64 {
|
||||
Some(#name::#ident)
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let from_i64_var = if clauses.is_empty() { quote!(_) } else { from_i64_var };
|
||||
|
||||
let res = quote! {
|
||||
#[allow(non_upper_case_globals)]
|
||||
#[allow(unused_qualifications)]
|
||||
const #dummy_const: () = {
|
||||
extern crate num_traits as _num_traits;
|
||||
|
||||
impl _num_traits::FromPrimitive for #name {
|
||||
#[allow(trivial_numeric_casts)]
|
||||
fn from_i64(#from_i64_var: i64) -> Option<Self> {
|
||||
#(#clauses else)* {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn from_u64(n: u64) -> Option<Self> {
|
||||
Self::from_i64(n as i64)
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
res.into()
|
||||
}
|
||||
|
||||
/// Derives [`num_traits::ToPrimitive`][to] for simple enums.
|
||||
///
|
||||
/// [to]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.ToPrimitive.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Simple enums can be derived:
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
///
|
||||
/// #[derive(ToPrimitive)]
|
||||
/// enum Color {
|
||||
/// Red,
|
||||
/// Blue,
|
||||
/// Green = 42,
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// Enums that contain data are not allowed:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
///
|
||||
/// #[derive(ToPrimitive)]
|
||||
/// enum Color {
|
||||
/// Rgb(u8, u8, u8),
|
||||
/// Hsv(u8, u8, u8),
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// Structs are not allowed:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # #[macro_use]
|
||||
/// # extern crate num_derive;
|
||||
/// #[derive(ToPrimitive)]
|
||||
/// struct Color {
|
||||
/// r: u8,
|
||||
/// g: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro_derive(ToPrimitive)]
|
||||
pub fn to_primitive(input: TokenStream) -> TokenStream {
|
||||
let ast: syn::DeriveInput = syn::parse(input).unwrap();
|
||||
let name = &ast.ident;
|
||||
let dummy_const = Ident::new(&format!("_IMPL_NUM_TO_PRIMITIVE_FOR_{}", name), Span::call_site());
|
||||
|
||||
let variants = match ast.data {
|
||||
Data::Enum(ref data_enum) => &data_enum.variants,
|
||||
_ => panic!("`ToPrimitive` can be applied only to the enums, {} is not an enum", name)
|
||||
};
|
||||
|
||||
let variants: Vec<_> = variants.iter()
|
||||
.map(|variant| {
|
||||
let ident = &variant.ident;
|
||||
match variant.fields {
|
||||
Fields::Unit => (),
|
||||
_ => {
|
||||
panic!("`ToPrimitive` can be applied only to unitary enums, {}::{} is either struct or tuple", name, ident)
|
||||
},
|
||||
}
|
||||
|
||||
// NB: We have to check each variant individually, because we'll only have `&self`
|
||||
// for the input. We can't move from that, and it might not be `Clone` or `Copy`.
|
||||
// (Otherwise we could just do `*self as i64` without a `match` at all.)
|
||||
quote!(#name::#ident => #name::#ident as i64)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let match_expr = if variants.is_empty() {
|
||||
// No variants found, so do not use Some to not to trigger `unreachable_code` lint
|
||||
quote! {
|
||||
match *self {}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
Some(match *self {
|
||||
#(#variants,)*
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let res = quote! {
|
||||
#[allow(non_upper_case_globals)]
|
||||
#[allow(unused_qualifications)]
|
||||
const #dummy_const: () = {
|
||||
extern crate num_traits as _num_traits;
|
||||
|
||||
impl _num_traits::ToPrimitive for #name {
|
||||
#[allow(trivial_numeric_casts)]
|
||||
fn to_i64(&self) -> Option<i64> {
|
||||
#match_expr
|
||||
}
|
||||
|
||||
fn to_u64(&self) -> Option<u64> {
|
||||
self.to_i64().map(|x| x as u64)
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
res.into()
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
// Copyright 2013-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 num as num_renamed;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
|
||||
#[derive(Debug, PartialEq, FromPrimitive, ToPrimitive)]
|
||||
enum Color {}
|
||||
|
||||
#[test]
|
||||
fn test_empty_enum() {
|
||||
let v: [Option<Color>; 1] = [num_renamed::FromPrimitive::from_u64(0)];
|
||||
|
||||
assert_eq!(v, [None]);
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
#![deny(trivial_numeric_casts)]
|
||||
extern crate num;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
|
||||
#[derive(FromPrimitive, ToPrimitive)]
|
||||
pub enum SomeEnum {
|
||||
A = 1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_trivial_numeric_casts() {
|
||||
use num::{FromPrimitive, ToPrimitive};
|
||||
assert!(SomeEnum::from_u64(1).is_some());
|
||||
assert!(SomeEnum::from_i64(-1).is_none());
|
||||
assert_eq!(SomeEnum::A.to_u64(), Some(1));
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#![deny(unused_qualifications)]
|
||||
extern crate num;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
use num::FromPrimitive;
|
||||
use num::ToPrimitive;
|
||||
|
||||
#[derive(FromPrimitive, ToPrimitive)]
|
||||
pub enum SomeEnum {
|
||||
A = 1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unused_qualifications() {
|
||||
assert!(SomeEnum::from_u64(1).is_some());
|
||||
assert!(SomeEnum::from_i64(-1).is_none());
|
||||
assert!(SomeEnum::A.to_i64().is_some());
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
// Copyright 2013-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_use]
|
||||
extern crate num_derive;
|
||||
|
||||
#[derive(Debug, FromPrimitive, ToPrimitive)]
|
||||
enum Direction {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
// Copyright 2013-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 num as num_renamed;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
|
||||
#[derive(Debug, PartialEq, FromPrimitive, ToPrimitive)]
|
||||
enum Color {
|
||||
Red,
|
||||
Blue,
|
||||
Green,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_primitive_for_trivial_case() {
|
||||
let v: [Option<Color>; 4] = [num_renamed::FromPrimitive::from_u64(0),
|
||||
num_renamed::FromPrimitive::from_u64(1),
|
||||
num_renamed::FromPrimitive::from_u64(2),
|
||||
num_renamed::FromPrimitive::from_u64(3)];
|
||||
|
||||
assert_eq!(v,
|
||||
[Some(Color::Red), Some(Color::Blue), Some(Color::Green), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_to_primitive_for_trivial_case() {
|
||||
let v: [Option<u64>; 3] = [num_renamed::ToPrimitive::to_u64(&Color::Red),
|
||||
num_renamed::ToPrimitive::to_u64(&Color::Blue),
|
||||
num_renamed::ToPrimitive::to_u64(&Color::Green)];
|
||||
|
||||
assert_eq!(v, [Some(0), Some(1), Some(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reflexive_for_trivial_case() {
|
||||
let before: [u64; 3] = [0, 1, 2];
|
||||
let after: Vec<Option<u64>> = before.iter()
|
||||
.map(|&x| -> Option<Color> { num_renamed::FromPrimitive::from_u64(x) })
|
||||
.map(|x| x.and_then(|x| num_renamed::ToPrimitive::to_u64(&x)))
|
||||
.collect();
|
||||
let before = before.into_iter().cloned().map(Some).collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(before, after);
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// Copyright 2013-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 = "full-syntax")]
|
||||
|
||||
extern crate num as num_renamed;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
|
||||
#[derive(Debug, PartialEq, FromPrimitive, ToPrimitive)]
|
||||
enum Color {
|
||||
Red,
|
||||
Blue = 5,
|
||||
Green,
|
||||
Alpha = (-3 - (-5isize)) - 10,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_primitive_for_enum_with_custom_value() {
|
||||
let v: [Option<Color>; 5] = [num_renamed::FromPrimitive::from_u64(0),
|
||||
num_renamed::FromPrimitive::from_u64(5),
|
||||
num_renamed::FromPrimitive::from_u64(6),
|
||||
num_renamed::FromPrimitive::from_u64(-8isize as u64),
|
||||
num_renamed::FromPrimitive::from_u64(3)];
|
||||
|
||||
assert_eq!(v,
|
||||
[Some(Color::Red), Some(Color::Blue), Some(Color::Green), Some(Color::Alpha), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_to_primitive_for_enum_with_custom_value() {
|
||||
let v: [Option<u64>; 4] = [num_renamed::ToPrimitive::to_u64(&Color::Red),
|
||||
num_renamed::ToPrimitive::to_u64(&Color::Blue),
|
||||
num_renamed::ToPrimitive::to_u64(&Color::Green),
|
||||
num_renamed::ToPrimitive::to_u64(&Color::Alpha)];
|
||||
|
||||
assert_eq!(v, [Some(0), Some(5), Some(6), Some(-8isize as u64)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reflexive_for_enum_with_custom_value() {
|
||||
let before: [u64; 3] = [0, 5, 6];
|
||||
let after: Vec<Option<u64>> = before.iter()
|
||||
.map(|&x| -> Option<Color> { num_renamed::FromPrimitive::from_u64(x) })
|
||||
.map(|x| x.and_then(|x| num_renamed::ToPrimitive::to_u64(&x)))
|
||||
.collect();
|
||||
let before = before.into_iter().cloned().map(Some).collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(before, after);
|
||||
}
|
Загрузка…
Ссылка в новой задаче