feat: add display UI with splash screen, dashboard, and RSSI sparkline
Implement full SSD1306 OLED display support: - Splash screen on boot (1.5s) with project name, version, board - Dashboard showing radio state, config, counters, RSSI/SNR - RSSI history sparkline (64-sample ring buffer, 2px-wide bars) - DisplayOn/DisplayOff host commands routed via dedicated channel - Pure render functions against generic DrawTarget (no hardware coupling) - Display on/off control bypasses radio task entirely Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
17624 files changed
+4564928
-38
No files matched your search
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"files":{".cargo_vcs_info.json":"3bde3eee94e30051823c5427b7507a61a32e53491efd2805330da57565dbed6c","Cargo.lock":"75a93570c0b69f52d44107effe5aabf17811db72887de6ea65b29d750602c935","Cargo.toml":"1daf014e9655e1e4d4550694412727b748134dccbf4b409aee7f8be65e729b70","Cargo.toml.orig":"987ccda0128805cde1b3ccf0b6db1dcf28a7193c1720254ce8e0c66d8dce2e23","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c87c7f72fd595c10bbe55b688ecb609e2e5b7f610410d558efce1ba8dc16f7b3","README.md":"46d76e9f126d95810106416a466ae9239bf9fb9012e217f57060ab3867ee9752","src/derive.rs":"3f223ee1b85365fc36ccd36e00d6925589cd80bfb617f4a67036889e1364fe21","src/lib.rs":"def6aa3b0837430fce9fee6954554ade21850d5e60b6d4017e5d128c3e7c2c52","src/macros.rs":"64c0722433c04f5d2f90a866f09a798fbade4cb85908b5befdbfb7036a8ce9c1","src/repr/array.rs":"2f4275ae7c43aae0b246e43b48b9c821c7e9fa7f7f204262dee5d86c0fc5a29e","src/repr/mod.rs":"4a9e9352504421d7dab65a34b2a81acb6bb1ea7d57d5cc6e31ad68b07729835d","src/repr/primitive.rs":"a1eb7c4bbc7576c1c19bb2ec485fd061c0043c5f3f4b6e123fd386be4f7ddb64","src/set.rs":"1d22bc8a43874bd1d8b74aa4545b28cf7981fcdbc653677ced19a8bd6bb4af61","src/traits.rs":"ec39f57249f995076800bc2f7d022c7c12e78fd9156a594cbbba4a086ac1496d","tests/bitset_basic_ops.rs":"58544a97329bc54fb69b20e63484d511acf0482b3726ad46667fa05316541c4d","tests/bitset_conversions.rs":"8d89c926264523f81190f1b2349c40ab825d508e549a1f837c17d50932907bb2","tests/bitset_explicit_repr.rs":"90f7b64de323c8ce6201c5ac9fdf274ec7b36694988ab9854685f643dae7660f","tests/bitset_serde_ops.rs":"b095d6d6f79d0c44a3377222b1fff7b4c5e574b70326dc4c03cec4104aec3795"},"package":"25b07a8dfbbbfc0064c0a6bdf9edcf966de6b1c33ce344bdeca3b41615452634"}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "a808e1de1f744c98cc33967da31513a78665ba2d"
|
||||
},
|
||||
"path_in_vcs": "enumset"
|
||||
}
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "bincode"
|
||||
version = "1.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08440b3dd222c3d0433e63e097463969485f112baff337dfdaca043a0d760570"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d25b7912bc28a04ab1b7715a68ea03aaa15662b43a1a4b2c480531fd19f8bf7e"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce154b9bea7fb0c8e8326e62d00354000c36e79770ff21b8c84e3aa267d9d531"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defmt"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "548d977b6da32fa1d1fda2876453da1e7df63ad0304c8b3dae4dbe7b96f39b78"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"defmt-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defmt-macros"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d4fc12a85bcf441cfe44344c4b72d58493178ce635338a3f3b78943aceb258e"
|
||||
dependencies = [
|
||||
"defmt-parser",
|
||||
"proc-macro-error2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defmt-parser"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
|
||||
dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumset"
|
||||
version = "1.1.10"
|
||||
dependencies = [
|
||||
"bincode",
|
||||
"defmt",
|
||||
"enumset_derive",
|
||||
"rustversion",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumset_derive"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f43e744e4ea338060faee68ed933e46e722fb7f3617e722a5772d7e856d8b3ce"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe4cd85333e22411419a0bcae1297d25e58c9443848b11dc6a86fefe8c78a661"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35"
|
||||
dependencies = [
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error-attr2"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
|
||||
dependencies = [
|
||||
"proc-macro-error-attr2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.97"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d61789d7719defeb74ea5fe81f2fdfdbd28a803847077cecce2ff14e1472f6f1"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.219"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.219"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.142"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b0949c3a6c842cbde3f1686d6eea5a010516deb7085f79db747562d4102f41e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc5b44b4ab9c2fdd0e0512e6bece8388e214c0749f5862b114cc5b7a25daf227"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.22.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.61"
|
||||
name = "enumset"
|
||||
version = "1.1.10"
|
||||
authors = ["Alissa Rao <aura@aura.moe>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "A library for creating compact sets of enums."
|
||||
documentation = "https://docs.rs/enumset/"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"enum",
|
||||
"bitset",
|
||||
]
|
||||
categories = ["data-structures"]
|
||||
license = "MIT/Apache-2.0"
|
||||
repository = "https://github.com/Lymia/enumset"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
|
||||
[badges.maintenance]
|
||||
status = "actively-developed"
|
||||
|
||||
[badges.travis-ci]
|
||||
branch = "master"
|
||||
repository = "Lymia/enumset"
|
||||
|
||||
[features]
|
||||
alloc = []
|
||||
proc-macro-crate = ["enumset_derive/proc-macro-crate"]
|
||||
serde2 = ["enumset_derive/serde2_deprecation_warning"]
|
||||
std = [
|
||||
"alloc",
|
||||
"enumset_derive/proc-macro-crate",
|
||||
"enumset_derive/std_deprecation_warning",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "enumset"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "bitset_basic_ops"
|
||||
path = "tests/bitset_basic_ops.rs"
|
||||
|
||||
[[test]]
|
||||
name = "bitset_conversions"
|
||||
path = "tests/bitset_conversions.rs"
|
||||
|
||||
[[test]]
|
||||
name = "bitset_explicit_repr"
|
||||
path = "tests/bitset_explicit_repr.rs"
|
||||
|
||||
[[test]]
|
||||
name = "bitset_serde_ops"
|
||||
path = "tests/bitset_serde_ops.rs"
|
||||
|
||||
[dependencies.defmt]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[dependencies.enumset_derive]
|
||||
version = "0.14.0"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.bincode]
|
||||
version = "1"
|
||||
features = ["i128"]
|
||||
|
||||
[dev-dependencies.rustversion]
|
||||
version = "1.0"
|
||||
|
||||
[dev-dependencies.serde_derive]
|
||||
version = "1"
|
||||
|
||||
[dev-dependencies.serde_json]
|
||||
version = "1"
|
||||
Vendored
+201
@@ -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.
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
Copyright (c) 2017-2025 Alissa Rao <aura@aura.moe>
|
||||
|
||||
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.
|
||||
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
# enumset
|
||||
|
||||
[](https://github.com/Lymia/enumset/actions/workflows/test.yml)
|
||||
[](https://crates.io/crates/enumset)
|
||||

|
||||
[](https://docs.rs/enumset)
|
||||
|
||||
A library for defining enums that can be used in compact bit sets. It supports
|
||||
`serde` and `#[no_std]` environments, and has basic support for using EnumSets
|
||||
in constants.
|
||||
|
||||
See [the documentation](https://docs.rs/enumset) for more information.
|
||||
|
||||
# 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 enumset by you, as defined in the Apache-2.0 license, shall be
|
||||
dual licensed as above, without any additional terms or conditions.
|
||||
Vendored
+152
@@ -0,0 +1,152 @@
|
||||
#[cfg(all(doc, feature = "serde"))]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(doc)]
|
||||
use crate::EnumSet;
|
||||
|
||||
/// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
|
||||
/// [`EnumSet`].
|
||||
///
|
||||
/// # Limitations
|
||||
///
|
||||
/// Currently, the following limitations apply to what kinds of enums this macro may be used with:
|
||||
///
|
||||
/// * The enum must have no data fields in any variant.
|
||||
/// * Variant discriminators must be zero or positive.
|
||||
/// * No variant may have a discriminator larger than `0xFFFFFFBF`.
|
||||
///
|
||||
/// # Additional Impls
|
||||
///
|
||||
/// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple
|
||||
/// other impls that are either required for the macro to work, or make the procedural macro more
|
||||
/// ergonomic to use.
|
||||
///
|
||||
/// A full list of traits implemented as is follows:
|
||||
///
|
||||
/// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet`
|
||||
/// to function properly. These automatic implementations may be suppressed using
|
||||
/// `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way.
|
||||
/// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are
|
||||
/// created to allow the crate to be used more ergonomically in expressions. These automatic
|
||||
/// implementations may be suppressed using `#[enumset(no_ops)]`.
|
||||
///
|
||||
/// # Options
|
||||
///
|
||||
/// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive.
|
||||
/// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax.
|
||||
///
|
||||
/// A full list of options available is as follows:
|
||||
///
|
||||
/// * `#[enumset(no_super_impls)]` prevents the procedural macro from generating implementations
|
||||
/// for the supertraits of `EnumSetType`. When this attribute is specified, implementations of
|
||||
/// [`Copy`], [`Clone`], [`Eq`], and [`PartialEq`] must be provided manually. These impls should
|
||||
/// function identically to the automatically derived versions, or unintentional behavior may be
|
||||
/// a result.
|
||||
/// * `#[enumset(no_ops)` prevents the procedural macro from implementing any operator traits.
|
||||
/// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate
|
||||
/// used in the generated code. When the `proc-macro-crate` feature is enabled, enumset parses
|
||||
/// `Cargo.toml` to determine the name of the crate, and this flag is unnecessary.
|
||||
/// * `#[enumset(map = "…")]` controls how enum variants are mapped to bits in the `EnumSet`. For
|
||||
/// more information, see the [Mapping Options](#mapping-options) section.
|
||||
/// * `#[enumset(repr = "…")]` is used to control the in-memory representation of `EnumSet`s. For
|
||||
/// more information, see the [Representation Options](#representation-options) section.
|
||||
///
|
||||
/// Additional feature may be specified when the `serde` feature is enabled. These options are
|
||||
/// ignored when `serde` is not enabled. For more information, see the
|
||||
/// [Serialization Options](#serialization-options) section.
|
||||
///
|
||||
/// ## Mapping Options
|
||||
///
|
||||
/// The following options exist to control how enum variants are mapped to bits in an `EnumSet`:
|
||||
///
|
||||
/// * `#[enumset(map = "lsb")]` maps an enum variant with a discriminator of `n` to the `n + 1`th
|
||||
/// least significant bit of the enumset. If no mapping is specified, this is used by default.
|
||||
/// * `#[enumset(map = "msb")]` maps an enum variant with a discriminator of `n` to the `n + 1`th
|
||||
/// most significant bit of the enumset. This requires an explicit integer representation or else
|
||||
/// compilation will fail.
|
||||
/// * `#[enumset(map = "compact")]` maps each enum variant to an unspecified bit in the set. This
|
||||
/// allows the library to use less memory than it may otherwise and allows any discrminator
|
||||
/// values to be used without issue.
|
||||
/// * `#[enumset(map = "mask")]` treats each enum variant's discriminator as a mask rather than a
|
||||
/// bit index. Each discriminant must be a power of two, and may be of arbitrary size.
|
||||
///
|
||||
/// ## Representation Options
|
||||
///
|
||||
/// The following options exist to control the in-memory representation of an `EnumSet`:
|
||||
///
|
||||
/// * `#[enumset(repr = "u…")]` forces the `EnumSet` to use a specific primitive integer type.
|
||||
/// Allowed types are `u8`, `u16`, `u32`, `u64` and `u128`. This allows the `EnumSet` to be
|
||||
/// safely used across FFI boundaries. Additionally, the procedural macro will generate an
|
||||
/// implementation of <code>[EnumSetTypeWithRepr]<Repr = R></code>.
|
||||
/// * `#[enumset(repr = "array")]` forces the `EnumSet` of this type to be backed with an array,
|
||||
/// even if all the variants could fit into a primitive numeric type.
|
||||
///
|
||||
/// By default, `enumset` tries to choose the representation most suitable to the type, but no
|
||||
/// guarantees are made about which it picks.
|
||||
///
|
||||
/// [EnumSetTypeWithRepr]: crate::traits::EnumSetTypeWithRepr
|
||||
///
|
||||
/// ## Serialization Options
|
||||
///
|
||||
/// The following options exist to control how an `EnumSet` is serialized with `serde`:
|
||||
///
|
||||
/// * `#[enumset(serialize_repr = "u…")]` causes the set to be serialized as a single integer
|
||||
/// of the corresponding primitive type.
|
||||
/// * `#[enumset(serialize_repr = "array")]` causes the set to be serialized as a list of `u64`s
|
||||
/// corresponding to the [array representation](EnumSet#array-representation) of the set.
|
||||
/// * `#[enumset(serialize_repr = "list")]` causes the set to be serialized as a list of enum
|
||||
/// variants. This requires your enum type implement [`Serialize`] and [`Deserialize`].
|
||||
/// * `#[enumset(serialize_repr = "map")]` causes the set to be serialized as map of enum variants
|
||||
/// to booleans. The set contains a value if the boolean is `true`. This requires your enum type
|
||||
/// implement `Serialize` and `Deserialize`.
|
||||
/// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error
|
||||
/// for unknown bits instead of silently ignoring them.
|
||||
///
|
||||
/// By default, `enumset` uses the smallest integer type that can contain all enum variants or an
|
||||
/// array if there is no such integer type.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Deriving a plain EnumSetType:
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// #[derive(EnumSetType)]
|
||||
/// pub enum Enum {
|
||||
/// A, B, C, D, E, F, G,
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Deriving a sparse EnumSetType:
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// #[derive(EnumSetType)]
|
||||
/// pub enum SparseEnum {
|
||||
/// A = 10, B = 20, C = 30, D = 127,
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Deriving an EnumSetType without adding ops:
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// #[derive(EnumSetType)]
|
||||
/// #[enumset(no_ops)]
|
||||
/// pub enum NoOpsEnum {
|
||||
/// A, B, C, D, E, F, G,
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [`Sub`]: core::ops::Sub
|
||||
/// [`BitAnd`]: core::ops::BitAnd
|
||||
/// [`BitOr`]: core::ops::BitOr
|
||||
/// [`BitXor`]: core::ops::BitXor
|
||||
/// [`Not`]: core::ops::Not
|
||||
#[cfg_attr(
|
||||
not(feature = "serde"),
|
||||
doc = "\n\n",
|
||||
doc = "[`Serialize`]: https://docs.rs/serde/latest/serde/trait.Serialize.html\n",
|
||||
doc = "[`Deserialize`]: https://docs.rs/serde/latest/serde/trait.Deserialize.html\n"
|
||||
)]
|
||||
pub use enumset_derive::EnumSetType;
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
#![no_std]
|
||||
#![deny(missing_docs)]
|
||||
#![allow(clippy::missing_safety_doc)] // The safety requirement is "use the procedural derive".
|
||||
#![allow(clippy::needless_range_loop)] // range loop style is clearer in most places in enumset
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
|
||||
//! A library for defining enums that can be used in compact bit sets. It supports arbitrarily
|
||||
//! large enums, and has very basic support for using them in constants.
|
||||
//!
|
||||
//! # Cargo Features
|
||||
//!
|
||||
//! The following cargo features are available for this crate:
|
||||
//!
|
||||
//! * `serde`: Allows serialization and deserialization of the types in this crate.
|
||||
//! * `alloc`: Enables the use of functions that requires an allocator.
|
||||
//! * `proc-macro-crate`: Enable the use of the `proc-macro-crate` crate to allow the renaming of
|
||||
//! the `enumset` crate in your user crate. This feature increases the MSRV to 1.69.0
|
||||
//!
|
||||
//! # Defining enums for use with EnumSet
|
||||
//!
|
||||
//! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use enumset::*;
|
||||
//! #[derive(EnumSetType, Debug)]
|
||||
//! pub enum Enum {
|
||||
//! A, B, C, D, E, F, G,
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! For more information on more advanced use cases, see the documentation for
|
||||
//! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
|
||||
//!
|
||||
//! # Working with EnumSets
|
||||
//!
|
||||
//! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
|
||||
//! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use enumset::*;
|
||||
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
|
||||
//! let new_set = Enum::A | Enum::C | Enum::G;
|
||||
//! assert_eq!(new_set.len(), 3);
|
||||
//! ```
|
||||
//!
|
||||
//! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
|
||||
//! enums with `#[derive(EnumSetType)]`:
|
||||
//! ```rust
|
||||
//! # use enumset::*;
|
||||
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
|
||||
//! // Intersection of sets
|
||||
//! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
|
||||
//! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
|
||||
//! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
|
||||
//!
|
||||
//! // Symmetric difference of sets
|
||||
//! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
|
||||
//! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
|
||||
//!
|
||||
//! // Difference of sets
|
||||
//! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
|
||||
//!
|
||||
//! // Complement of sets
|
||||
//! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
|
||||
//! ```
|
||||
//!
|
||||
//! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use enumset::*;
|
||||
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
|
||||
//! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
|
||||
//! assert_eq!(CONST_SET, Enum::A | Enum::B);
|
||||
//! ```
|
||||
//!
|
||||
//! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use enumset::*;
|
||||
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
|
||||
//! let mut set = EnumSet::new();
|
||||
//! set.insert(Enum::A);
|
||||
//! set.insert_all(Enum::E | Enum::G);
|
||||
//! assert!(set.contains(Enum::A));
|
||||
//! assert!(!set.contains(Enum::B));
|
||||
//! assert_eq!(set, Enum::A | Enum::E | Enum::G);
|
||||
//! ```
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
extern crate alloc;
|
||||
|
||||
mod macros;
|
||||
|
||||
mod derive;
|
||||
mod repr;
|
||||
mod set;
|
||||
mod traits;
|
||||
|
||||
pub use crate::derive::EnumSetType;
|
||||
pub use crate::macros::__internal;
|
||||
pub use crate::set::{EnumSet, EnumSetIter};
|
||||
pub use crate::traits::{EnumSetType, EnumSetTypeWithRepr};
|
||||
Vendored
+305
@@ -0,0 +1,305 @@
|
||||
/// Everything in this module is internal API and may change at any time.
|
||||
#[doc(hidden)]
|
||||
pub mod __internal {
|
||||
/// A reexport of core to allow our macros to be generic to std vs core.
|
||||
pub use ::core as core_export;
|
||||
|
||||
/// A reexport of serde so our users don't have to also have a serde dependency.
|
||||
#[cfg(feature = "serde")]
|
||||
pub use serde;
|
||||
|
||||
/// Reexports of internal types
|
||||
pub use crate::{
|
||||
repr::{ArrayRepr, EnumSetTypeRepr},
|
||||
traits::{EnumSetConstHelper, EnumSetTypePrivate},
|
||||
};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! __if_serde {
|
||||
($($tt:tt)*) => {
|
||||
$($tt)*
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "serde"))]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! __if_serde {
|
||||
($($tt:tt)*) => {};
|
||||
}
|
||||
|
||||
/// Macro to wrap serde-related code generated by the derive, discarding it
|
||||
/// if serde support is not enabled.
|
||||
pub use __if_serde;
|
||||
|
||||
pub use crate::macros::set;
|
||||
}
|
||||
|
||||
/// Helper functions for sets.
|
||||
pub mod set {
|
||||
use crate::__internal::EnumSetConstHelper;
|
||||
use crate::{EnumSet, EnumSetType};
|
||||
|
||||
/// Retrieves the helper used in constant time operations.
|
||||
#[inline(always)]
|
||||
pub const fn op_helper<T: EnumSetConstHelper>(_: &T) -> T::ConstOpHelper {
|
||||
T::CONST_OP_HELPER
|
||||
}
|
||||
|
||||
/// Retrieves the helper used in constant time conversions.
|
||||
#[inline(always)]
|
||||
pub const fn init_helper<T: EnumSetConstHelper>(_: &T) -> T::ConstInitHelper {
|
||||
T::CONST_INIT_HELPER
|
||||
}
|
||||
|
||||
/// Gets the underlying repr from an EnumSet
|
||||
#[inline(always)]
|
||||
pub const fn get<T: EnumSetType>(set: EnumSet<T>) -> T::Repr {
|
||||
set.repr
|
||||
}
|
||||
|
||||
/// Constructs an EnumSet from the underlying repr
|
||||
#[inline(always)]
|
||||
pub const fn new<T: EnumSetType>(set: T::Repr) -> EnumSet<T> {
|
||||
EnumSet { repr: set }
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a EnumSet literal, which can be used in const contexts.
|
||||
///
|
||||
/// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
|
||||
/// type, or an error will occur at compile-time.
|
||||
///
|
||||
/// This macro accepts trailing `|`s to allow easier use in other macros.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use `Type::A | Type::B | Type::C` instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
|
||||
/// assert_eq!(CONST_SET, Enum::A | Enum::B);
|
||||
/// ```
|
||||
///
|
||||
/// This macro is strongly typed. For example, the following will not compile:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
|
||||
/// let type_error = enum_set!(Enum::A | Enum2::B);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set {
|
||||
($(|)*) => {
|
||||
$crate::EnumSet::empty()
|
||||
};
|
||||
($value:path $(|)*) => {
|
||||
{
|
||||
$crate::__internal::set::init_helper(&$value).const_only($value)
|
||||
}
|
||||
};
|
||||
($value:path | $($rest:path)|* $(|)*) => {
|
||||
$crate::enum_set_union!($value, $($rest,)*)
|
||||
};
|
||||
}
|
||||
|
||||
/// Computes the union of multiple enums or constants enumset at compile time.
|
||||
///
|
||||
/// The syntax used is `enum_set_union!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent of
|
||||
/// `ENUM_A | ENUM_B | ENUM_C` at compile time. Each variant must be of the same type, or an error
|
||||
/// will occur at compile-time.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use the `|` operator instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set_union!(Enum::A, Enum::B);
|
||||
/// assert_eq!(CONST_SET, Enum::A | Enum::B);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set_union {
|
||||
($value:path $(,)?) => {
|
||||
$crate::enum_set!($value)
|
||||
};
|
||||
($value:path, $($rest:path),* $(,)?) => {
|
||||
{
|
||||
let op_helper = $crate::__internal::set::op_helper(&$value);
|
||||
let value = $crate::enum_set!($value);
|
||||
$(let value = {
|
||||
let new = $crate::enum_set!($rest);
|
||||
op_helper.const_union(value, new)
|
||||
};)*
|
||||
value
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Computes the intersection of multiple enums or constants enumset at compile time.
|
||||
///
|
||||
/// The syntax used is `enum_set_intersection!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent
|
||||
/// of `ENUM_A & ENUM_B & ENUM_C` at compile time. Each variant must be of the same type, or an
|
||||
/// error will occur at compile-time.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use the `&` operator instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
|
||||
/// const SET_A: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
|
||||
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set_intersection!(SET_A, SET_B);
|
||||
/// assert_eq!(CONST_SET, Enum::B);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set_intersection {
|
||||
($value:path $(,)?) => {
|
||||
$crate::enum_set!($value)
|
||||
};
|
||||
($value:path, $($rest:path),* $(,)?) => {
|
||||
{
|
||||
let op_helper = $crate::__internal::set::op_helper(&$value);
|
||||
let value = $crate::enum_set!($value);
|
||||
$(let value = {
|
||||
let new = $crate::enum_set!($rest);
|
||||
op_helper.const_intersection(value, new)
|
||||
};)*
|
||||
value
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Computes the complement of an enums or constants enumset at compile time.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use the `!` operator instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// #[derive(EnumSetType, Debug)]
|
||||
/// enum Enum { A, B, C, D }
|
||||
///
|
||||
/// const SET: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set_complement!(SET);
|
||||
/// assert_eq!(CONST_SET, Enum::A | Enum::D);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set_complement {
|
||||
($value:path $(,)?) => {{
|
||||
let op_helper = $crate::__internal::set::op_helper(&$value);
|
||||
let value = $crate::enum_set!($value);
|
||||
op_helper.const_complement(value)
|
||||
}};
|
||||
}
|
||||
|
||||
/// Computes the difference of multiple enums or constants enumset at compile time.
|
||||
///
|
||||
/// The syntax used is `enum_set_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent
|
||||
/// of `ENUM_A - ENUM_B - ENUM_C` at compile time. Each variant must be of the same type, or an
|
||||
/// error will occur at compile-time.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use the `-` operator instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
|
||||
/// const SET_A: EnumSet<Enum> = enum_set!(Enum::A | Enum::B | Enum::D);
|
||||
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set_symmetric_difference!(SET_A, SET_B);
|
||||
/// assert_eq!(CONST_SET, Enum::A | Enum::C | Enum::D);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set_difference {
|
||||
($value:path $(,)?) => {
|
||||
$crate::enum_set!($value)
|
||||
};
|
||||
($value:path, $($rest:path),* $(,)?) => {
|
||||
{
|
||||
let op_helper = $crate::__internal::set::op_helper(&$value);
|
||||
let value = $crate::enum_set!($value);
|
||||
$(let value = {
|
||||
let new = $crate::enum_set!($rest);
|
||||
op_helper.const_intersection(value, op_helper.const_complement(new))
|
||||
};)*
|
||||
value
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Computes the symmetric difference of multiple enums or constants enumset at compile time.
|
||||
///
|
||||
/// The syntax used is `enum_set_symmetric_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the
|
||||
/// equivalent of `ENUM_A ^ ENUM_B ^ ENUM_C` at compile time. Each variant must be of the same
|
||||
/// type, or an error will occur at compile-time.
|
||||
///
|
||||
/// # Performance
|
||||
///
|
||||
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
|
||||
/// significantly slower than normal code outside const contexts.
|
||||
///
|
||||
/// In normal code, directly use the `^` operator instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # use enumset::*;
|
||||
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
|
||||
/// const SET_A: EnumSet<Enum> = EnumSet::all();
|
||||
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
|
||||
/// const CONST_SET: EnumSet<Enum> = enum_set_difference!(SET_A, SET_B);
|
||||
/// assert_eq!(CONST_SET, Enum::A | Enum::D);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! enum_set_symmetric_difference {
|
||||
($value:path $(,)?) => {
|
||||
$crate::enum_set!($value)
|
||||
};
|
||||
($value:path, $($rest:path),* $(,)?) => {
|
||||
{
|
||||
let op_helper = $crate::__internal::set::op_helper(&$value);
|
||||
let value = $crate::enum_set!($value);
|
||||
$(let value = {
|
||||
let new = $crate::enum_set!($rest);
|
||||
op_helper.const_symmetric_difference(value, new)
|
||||
};)*
|
||||
value
|
||||
}
|
||||
};
|
||||
}
|
||||
Vendored
+317
@@ -0,0 +1,317 @@
|
||||
use crate::repr::primitive::PrimitiveIter;
|
||||
use crate::repr::EnumSetTypeRepr;
|
||||
use core::ops::*;
|
||||
|
||||
/// An implementation of `EnumSetTypeRepr` based on an arbitrary size array.
|
||||
///
|
||||
/// `N` **must** not be `0`, or else everything will break.
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
|
||||
pub struct ArrayRepr<const N: usize>(pub [u64; N]);
|
||||
impl<const N: usize> ArrayRepr<N> {
|
||||
fn split_bit(bit: u32) -> (usize, u32) {
|
||||
(bit as usize / 64, bit % 64)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> BitAnd for ArrayRepr<N> {
|
||||
type Output = Self;
|
||||
fn bitand(mut self, rhs: Self) -> Self::Output {
|
||||
for i in 0..N {
|
||||
self.0[i] &= rhs.0[i];
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<const N: usize> BitOr for ArrayRepr<N> {
|
||||
type Output = Self;
|
||||
fn bitor(mut self, rhs: Self) -> Self::Output {
|
||||
for i in 0..N {
|
||||
self.0[i] |= rhs.0[i];
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<const N: usize> BitXor for ArrayRepr<N> {
|
||||
type Output = Self;
|
||||
fn bitxor(mut self, rhs: Self) -> Self::Output {
|
||||
for i in 0..N {
|
||||
self.0[i] ^= rhs.0[i];
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<const N: usize> Not for ArrayRepr<N> {
|
||||
type Output = Self;
|
||||
fn not(mut self) -> Self::Output {
|
||||
for i in 0..N {
|
||||
self.0[i] = !self.0[i];
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> EnumSetTypeRepr for ArrayRepr<N> {
|
||||
const PREFERRED_ARRAY_LEN: usize = N;
|
||||
const WIDTH: u32 = N as u32 * 64;
|
||||
const EMPTY: Self = ArrayRepr([0; N]);
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.0.iter().all(|x| *x == 0)
|
||||
}
|
||||
|
||||
fn add_bit(&mut self, bit: u32) {
|
||||
let (idx, bit) = Self::split_bit(bit);
|
||||
self.0[idx].add_bit(bit);
|
||||
}
|
||||
fn remove_bit(&mut self, bit: u32) {
|
||||
let (idx, bit) = Self::split_bit(bit);
|
||||
self.0[idx].remove_bit(bit);
|
||||
}
|
||||
fn has_bit(&self, bit: u32) -> bool {
|
||||
let (idx, bit) = Self::split_bit(bit);
|
||||
self.0[idx].has_bit(bit)
|
||||
}
|
||||
|
||||
fn count_ones(&self) -> u32 {
|
||||
self.0.iter().map(|x| x.count_ones()).sum()
|
||||
}
|
||||
|
||||
fn and_not(&self, other: Self) -> Self {
|
||||
let mut new = Self([0; N]);
|
||||
for i in 0..N {
|
||||
new.0[i] = self.0[i] & !other.0[i];
|
||||
}
|
||||
new
|
||||
}
|
||||
|
||||
type Iter = ArrayIter<N>;
|
||||
fn iter(self) -> Self::Iter {
|
||||
ArrayIter::new(self)
|
||||
}
|
||||
|
||||
fn from_u8(v: u8) -> Self {
|
||||
Self::from_u64(v as u64)
|
||||
}
|
||||
fn from_u16(v: u16) -> Self {
|
||||
Self::from_u64(v as u64)
|
||||
}
|
||||
fn from_u32(v: u32) -> Self {
|
||||
Self::from_u64(v as u64)
|
||||
}
|
||||
fn from_u64(v: u64) -> Self {
|
||||
let mut new = Self([0; N]);
|
||||
new.0[0] = v;
|
||||
new
|
||||
}
|
||||
fn from_u128(v: u128) -> Self {
|
||||
let mut new = Self([0; N]);
|
||||
new.0[0] = v as u64;
|
||||
if N != 1 {
|
||||
new.0[1] = (v >> 64) as u64;
|
||||
}
|
||||
new
|
||||
}
|
||||
fn from_usize(v: usize) -> Self {
|
||||
Self::from_u64(v as u64)
|
||||
}
|
||||
|
||||
fn from_u8_opt(v: u8) -> Option<Self> {
|
||||
Some(Self::from_u8(v))
|
||||
}
|
||||
fn from_u16_opt(v: u16) -> Option<Self> {
|
||||
Some(Self::from_u16(v))
|
||||
}
|
||||
fn from_u32_opt(v: u32) -> Option<Self> {
|
||||
Some(Self::from_u32(v))
|
||||
}
|
||||
fn from_u64_opt(v: u64) -> Option<Self> {
|
||||
Some(Self::from_u64(v))
|
||||
}
|
||||
fn from_u128_opt(v: u128) -> Option<Self> {
|
||||
if N == 1 && (v >> 64) != 0 {
|
||||
None
|
||||
} else {
|
||||
Some(Self::from_u128(v))
|
||||
}
|
||||
}
|
||||
fn from_usize_opt(v: usize) -> Option<Self> {
|
||||
Some(Self::from_usize(v))
|
||||
}
|
||||
|
||||
fn to_u8(&self) -> u8 {
|
||||
self.to_u64().to_u8()
|
||||
}
|
||||
fn to_u16(&self) -> u16 {
|
||||
self.to_u64().to_u16()
|
||||
}
|
||||
fn to_u32(&self) -> u32 {
|
||||
self.to_u64().to_u32()
|
||||
}
|
||||
fn to_u64(&self) -> u64 {
|
||||
self.0[0]
|
||||
}
|
||||
fn to_u128(&self) -> u128 {
|
||||
let hi = if N == 1 { 0 } else { (self.0[1] as u128) << 64 };
|
||||
self.0[0] as u128 | hi
|
||||
}
|
||||
fn to_usize(&self) -> usize {
|
||||
self.to_u64().to_usize()
|
||||
}
|
||||
|
||||
fn to_u8_opt(&self) -> Option<u8> {
|
||||
self.to_u64_opt().and_then(|x| x.to_u8_opt())
|
||||
}
|
||||
fn to_u16_opt(&self) -> Option<u16> {
|
||||
self.to_u64_opt().and_then(|x| x.to_u16_opt())
|
||||
}
|
||||
fn to_u32_opt(&self) -> Option<u32> {
|
||||
self.to_u64_opt().and_then(|x| x.to_u32_opt())
|
||||
}
|
||||
fn to_u64_opt(&self) -> Option<u64> {
|
||||
for i in 1..N {
|
||||
if self.0[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(self.to_u64())
|
||||
}
|
||||
fn to_u128_opt(&self) -> Option<u128> {
|
||||
for i in 2..N {
|
||||
if self.0[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(self.to_u128())
|
||||
}
|
||||
fn to_usize_opt(&self) -> Option<usize> {
|
||||
self.to_u64_opt().and_then(|x| x.to_usize_opt())
|
||||
}
|
||||
|
||||
fn to_u64_array<const O: usize>(&self) -> [u64; O] {
|
||||
let mut array = [0; O];
|
||||
let copy_len = if N < O { N } else { O };
|
||||
array[..copy_len].copy_from_slice(&self.0[..copy_len]);
|
||||
array
|
||||
}
|
||||
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]> {
|
||||
if N > O {
|
||||
for i in O..N {
|
||||
if self.0[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(self.to_u64_array())
|
||||
}
|
||||
|
||||
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self {
|
||||
ArrayRepr(ArrayRepr::<O>(v).to_u64_array::<N>())
|
||||
}
|
||||
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self> {
|
||||
ArrayRepr::<O>(v).to_u64_array_opt::<N>().map(ArrayRepr)
|
||||
}
|
||||
|
||||
fn to_u64_slice(&self, out: &mut [u64]) {
|
||||
let copy_len = if N < out.len() { N } else { out.len() };
|
||||
out[..copy_len].copy_from_slice(&self.0[..copy_len]);
|
||||
for i in copy_len..out.len() {
|
||||
out[i] = 0;
|
||||
}
|
||||
}
|
||||
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> {
|
||||
if N > out.len() {
|
||||
for i in out.len()..N {
|
||||
if self.0[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.to_u64_slice(out);
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn from_u64_slice(v: &[u64]) -> Self {
|
||||
let mut new = ArrayRepr([0; N]);
|
||||
let copy_len = if N < v.len() { N } else { v.len() };
|
||||
new.0[..copy_len].copy_from_slice(&v[..copy_len]);
|
||||
new
|
||||
}
|
||||
fn from_u64_slice_opt(v: &[u64]) -> Option<Self> {
|
||||
if v.len() > N {
|
||||
for i in N..v.len() {
|
||||
if v[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Self::from_u64_slice(v))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ArrayIter<const N: usize> {
|
||||
data: [PrimitiveIter<u64>; N],
|
||||
done: bool,
|
||||
idx_f: usize,
|
||||
idx_r: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> ArrayIter<N> {
|
||||
pub fn new(array: ArrayRepr<N>) -> Self {
|
||||
let mut new = [PrimitiveIter(0); N];
|
||||
for i in 0..N {
|
||||
new[i] = PrimitiveIter(array.0[i])
|
||||
}
|
||||
ArrayIter { data: new, done: false, idx_f: 0, idx_r: N - 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Iterator for ArrayIter<N> {
|
||||
type Item = u32;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.done {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
if let Some(x) = unsafe { self.data.get_unchecked_mut(self.idx_f).next() } {
|
||||
return Some(self.idx_f as u32 * 64 + x);
|
||||
} else {
|
||||
if self.idx_f == N - 1 || self.idx_f > self.idx_r {
|
||||
break;
|
||||
}
|
||||
self.idx_f += 1;
|
||||
}
|
||||
}
|
||||
self.done = true;
|
||||
None
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let mut sum = 0;
|
||||
for i in self.idx_f..self.idx_r + 1 {
|
||||
sum += self.data[i].0.count_ones() as usize;
|
||||
}
|
||||
(sum, Some(sum))
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> DoubleEndedIterator for ArrayIter<N> {
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
if self.done {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
if let Some(x) = unsafe { self.data.get_unchecked_mut(self.idx_r).next_back() } {
|
||||
return Some(self.idx_r as u32 * 64 + x);
|
||||
} else {
|
||||
if self.idx_r == 0 || self.idx_f > self.idx_r {
|
||||
break;
|
||||
}
|
||||
self.idx_r -= 1;
|
||||
}
|
||||
}
|
||||
self.done = true;
|
||||
None
|
||||
}
|
||||
}
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
#![allow(missing_docs)]
|
||||
|
||||
mod array;
|
||||
mod primitive;
|
||||
|
||||
use core::fmt::Debug;
|
||||
use core::hash::Hash;
|
||||
use core::ops::*;
|
||||
|
||||
/// A trait marking valid underlying bitset storage types and providing the
|
||||
/// operations `EnumSet` and related types use.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Note that `iter` *MUST* be implemented correctly and only return bits that
|
||||
/// are actually set in the representation, or else it will cause undefined
|
||||
/// behavior upstream in `EnumSet`.
|
||||
pub trait EnumSetTypeRepr :
|
||||
// Basic traits used to derive traits
|
||||
Copy +
|
||||
Ord +
|
||||
Eq +
|
||||
Debug +
|
||||
Hash +
|
||||
// Operations used by enumset
|
||||
BitAnd<Output = Self> +
|
||||
BitOr<Output = Self> +
|
||||
BitXor<Output = Self> +
|
||||
Not<Output = Self> +
|
||||
{
|
||||
const PREFERRED_ARRAY_LEN: usize;
|
||||
const WIDTH: u32;
|
||||
const EMPTY: Self;
|
||||
|
||||
fn is_empty(&self) -> bool;
|
||||
|
||||
fn add_bit(&mut self, bit: u32);
|
||||
fn remove_bit(&mut self, bit: u32);
|
||||
fn has_bit(&self, bit: u32) -> bool;
|
||||
|
||||
fn count_ones(&self) -> u32;
|
||||
|
||||
fn and_not(&self, other: Self) -> Self;
|
||||
|
||||
type Iter: Iterator<Item = u32> + DoubleEndedIterator + Clone + Debug;
|
||||
fn iter(self) -> Self::Iter;
|
||||
|
||||
fn from_u8(v: u8) -> Self;
|
||||
fn from_u16(v: u16) -> Self;
|
||||
fn from_u32(v: u32) -> Self;
|
||||
fn from_u64(v: u64) -> Self;
|
||||
fn from_u128(v: u128) -> Self;
|
||||
fn from_usize(v: usize) -> Self;
|
||||
|
||||
fn to_u8(&self) -> u8;
|
||||
fn to_u16(&self) -> u16;
|
||||
fn to_u32(&self) -> u32;
|
||||
fn to_u64(&self) -> u64;
|
||||
fn to_u128(&self) -> u128;
|
||||
fn to_usize(&self) -> usize;
|
||||
|
||||
fn from_u8_opt(v: u8) -> Option<Self>;
|
||||
fn from_u16_opt(v: u16) -> Option<Self>;
|
||||
fn from_u32_opt(v: u32) -> Option<Self>;
|
||||
fn from_u64_opt(v: u64) -> Option<Self>;
|
||||
fn from_u128_opt(v: u128) -> Option<Self>;
|
||||
fn from_usize_opt(v: usize) -> Option<Self>;
|
||||
|
||||
fn to_u8_opt(&self) -> Option<u8>;
|
||||
fn to_u16_opt(&self) -> Option<u16>;
|
||||
fn to_u32_opt(&self) -> Option<u32>;
|
||||
fn to_u64_opt(&self) -> Option<u64>;
|
||||
fn to_u128_opt(&self) -> Option<u128>;
|
||||
fn to_usize_opt(&self) -> Option<usize>;
|
||||
|
||||
fn to_u64_array<const O: usize>(&self) -> [u64; O];
|
||||
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]>;
|
||||
|
||||
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self;
|
||||
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self>;
|
||||
|
||||
fn to_u64_slice(&self, out: &mut [u64]);
|
||||
#[must_use]
|
||||
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()>;
|
||||
|
||||
fn from_u64_slice(v: &[u64]) -> Self;
|
||||
fn from_u64_slice_opt(v: &[u64]) -> Option<Self>;
|
||||
}
|
||||
|
||||
pub use array::ArrayRepr;
|
||||
Vendored
+309
@@ -0,0 +1,309 @@
|
||||
use crate::repr::EnumSetTypeRepr;
|
||||
|
||||
pub trait Primitive {
|
||||
fn leading_zeros(&self) -> u32;
|
||||
fn trailing_zeros(&self) -> u32;
|
||||
}
|
||||
|
||||
macro_rules! prim {
|
||||
($name:ty, $width:expr, $preferred_array_len:expr) => {
|
||||
const _: () = {
|
||||
fn lo(v: $name) -> u64 {
|
||||
v as u64
|
||||
}
|
||||
fn hi(v: $name) -> u64 {
|
||||
((v as u128) >> 64) as u64
|
||||
}
|
||||
|
||||
impl EnumSetTypeRepr for $name {
|
||||
const PREFERRED_ARRAY_LEN: usize = $preferred_array_len;
|
||||
const WIDTH: u32 = $width;
|
||||
const EMPTY: Self = 0;
|
||||
|
||||
#[inline(always)]
|
||||
fn is_empty(&self) -> bool {
|
||||
*self == 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn add_bit(&mut self, bit: u32) {
|
||||
*self |= 1 << bit as $name;
|
||||
}
|
||||
#[inline(always)]
|
||||
fn remove_bit(&mut self, bit: u32) {
|
||||
*self &= !(1 << bit as $name);
|
||||
}
|
||||
#[inline(always)]
|
||||
fn has_bit(&self, bit: u32) -> bool {
|
||||
(self & (1 << bit as $name)) != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn count_ones(&self) -> u32 {
|
||||
(*self).count_ones()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn and_not(&self, other: Self) -> Self {
|
||||
(*self) & !other
|
||||
}
|
||||
|
||||
type Iter = PrimitiveIter<Self>;
|
||||
#[inline]
|
||||
fn iter(self) -> Self::Iter {
|
||||
PrimitiveIter(self)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_u8(v: u8) -> Self {
|
||||
v as $name
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u16(v: u16) -> Self {
|
||||
v as $name
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u32(v: u32) -> Self {
|
||||
v as $name
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u64(v: u64) -> Self {
|
||||
v as $name
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u128(v: u128) -> Self {
|
||||
v as $name
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_usize(v: usize) -> Self {
|
||||
v as $name
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_u8(&self) -> u8 {
|
||||
(*self) as u8
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u16(&self) -> u16 {
|
||||
(*self) as u16
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u32(&self) -> u32 {
|
||||
(*self) as u32
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u64(&self) -> u64 {
|
||||
(*self) as u64
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u128(&self) -> u128 {
|
||||
(*self) as u128
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_usize(&self) -> usize {
|
||||
(*self) as usize
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_u8_opt(v: u8) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u16_opt(v: u16) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u32_opt(v: u32) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u64_opt(v: u64) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u128_opt(v: u128) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_usize_opt(v: usize) -> Option<Self> {
|
||||
v.try_into().ok()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_u8_opt(&self) -> Option<u8> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u16_opt(&self) -> Option<u16> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u32_opt(&self) -> Option<u32> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u64_opt(&self) -> Option<u64> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u128_opt(&self) -> Option<u128> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_usize_opt(&self) -> Option<usize> {
|
||||
(*self).try_into().ok()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_u64_array<const O: usize>(&self) -> [u64; O] {
|
||||
let mut array = [0; O];
|
||||
if O > 0 {
|
||||
array[0] = lo(*self);
|
||||
}
|
||||
if O > 1 && $preferred_array_len == 2 {
|
||||
array[1] = hi(*self);
|
||||
}
|
||||
array
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]> {
|
||||
if O == 0 && *self != 0 {
|
||||
None
|
||||
} else if O == 1 && hi(*self) != 0 {
|
||||
None
|
||||
} else {
|
||||
Some(self.to_u64_array())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self {
|
||||
if O == 0 {
|
||||
0
|
||||
} else if O > 1 && $preferred_array_len == 2 {
|
||||
Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64))
|
||||
} else {
|
||||
Self::from_u64(v[0])
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self> {
|
||||
if O == 0 {
|
||||
Some(0)
|
||||
} else if O == 1 {
|
||||
Self::from_u64_opt(v[0])
|
||||
} else {
|
||||
for i in 2..O {
|
||||
if v[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_u64_slice(&self, out: &mut [u64]) {
|
||||
if out.len() > 0 {
|
||||
out[0] = lo(*self);
|
||||
}
|
||||
if out.len() > 1 && $preferred_array_len == 2 {
|
||||
out[1] = hi(*self);
|
||||
}
|
||||
for i in $preferred_array_len..out.len() {
|
||||
out[i] = 0;
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> {
|
||||
if out.len() == 0 && *self != 0 {
|
||||
None
|
||||
} else if out.len() == 1 && hi(*self) != 0 {
|
||||
None
|
||||
} else {
|
||||
self.to_u64_slice(out);
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn from_u64_slice(v: &[u64]) -> Self {
|
||||
if v.len() == 0 {
|
||||
0
|
||||
} else if v.len() > 1 && $preferred_array_len == 2 {
|
||||
Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64))
|
||||
} else {
|
||||
Self::from_u64(v[0])
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_u64_slice_opt(v: &[u64]) -> Option<Self> {
|
||||
if v.len() == 0 {
|
||||
Some(0)
|
||||
} else if v.len() == 1 {
|
||||
Self::from_u64_opt(v[0])
|
||||
} else {
|
||||
for i in 2..v.len() {
|
||||
if v[i] != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Primitive for $name {
|
||||
#[inline(always)]
|
||||
fn leading_zeros(&self) -> u32 {
|
||||
(*self).leading_zeros()
|
||||
}
|
||||
#[inline(always)]
|
||||
fn trailing_zeros(&self) -> u32 {
|
||||
(*self).trailing_zeros()
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
prim!(u8, 8, 1);
|
||||
prim!(u16, 16, 1);
|
||||
prim!(u32, 32, 1);
|
||||
prim!(u64, 64, 1);
|
||||
prim!(u128, 128, 2);
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#[repr(transparent)]
|
||||
pub struct PrimitiveIter<T: EnumSetTypeRepr + Primitive>(pub T);
|
||||
|
||||
impl<T: EnumSetTypeRepr + Primitive> Iterator for PrimitiveIter<T> {
|
||||
type Item = u32;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.0.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let bit = self.0.trailing_zeros();
|
||||
self.0.remove_bit(bit);
|
||||
Some(bit)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let left = self.0.count_ones() as usize;
|
||||
(left, Some(left))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetTypeRepr + Primitive> DoubleEndedIterator for PrimitiveIter<T> {
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
if self.0.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let bit = T::WIDTH - 1 - self.0.leading_zeros();
|
||||
self.0.remove_bit(bit);
|
||||
Some(bit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetTypeRepr + Primitive> ExactSizeIterator for PrimitiveIter<T> {}
|
||||
Vendored
+917
@@ -0,0 +1,917 @@
|
||||
use crate::repr::EnumSetTypeRepr;
|
||||
use crate::traits::{EnumSetConstHelper, EnumSetType};
|
||||
use crate::EnumSetTypeWithRepr;
|
||||
use core::cmp::Ordering;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
use core::hash::{Hash, Hasher};
|
||||
use core::iter::Sum;
|
||||
use core::ops::{
|
||||
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Sub, SubAssign,
|
||||
};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An efficient set type for enums.
|
||||
///
|
||||
/// It is implemented using a bitset stored using the smallest integer that can fit all bits
|
||||
/// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in
|
||||
/// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
|
||||
///
|
||||
/// # Numeric representation
|
||||
///
|
||||
/// `EnumSet` is internally implemented using integer types, and as such can be easily converted
|
||||
/// from and to numbers.
|
||||
///
|
||||
/// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
|
||||
/// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to
|
||||
/// any variant are always unset.
|
||||
///
|
||||
/// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum
|
||||
/// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit
|
||||
/// (corresponding to a mask of e.g. `1 << enum as u32`).
|
||||
///
|
||||
/// The [`#[enumset(map = "…")]`](derive@crate::EnumSetType#mapping-options) attribute can be used
|
||||
/// to control this mapping.
|
||||
///
|
||||
/// # Array representation
|
||||
///
|
||||
/// Sets with more than 128 variants are instead stored with an underlying array of `u64`s. This
|
||||
/// is treated as if it was a single large integer. The `n`th least significant bit of this integer
|
||||
/// is stored in the `n % 64`th least significant bit of the `n / 64`th element in the array.
|
||||
///
|
||||
/// # Serialization
|
||||
///
|
||||
/// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
|
||||
/// the `serde` crate.
|
||||
///
|
||||
/// By default, `EnumSet` is serialized by directly writing out a single integer containing the
|
||||
/// numeric representation of the bitset. The integer type used is the smallest one that can fit
|
||||
/// the largest variant in the enum. If no integer type is large enough, instead the `EnumSet` is
|
||||
/// serialized as an array of `u64`s containing the array representation. Unknown bits are ignored
|
||||
/// and silently removed from the bitset when deserializing.
|
||||
///
|
||||
/// The exact serialization format can be controlled with additional attributes on the enum type.
|
||||
/// For more information, see the documentation for
|
||||
/// [Serialization Options](derive@crate::EnumSetType#serialization-options).
|
||||
///
|
||||
/// # FFI Safety
|
||||
///
|
||||
/// By default, there are no guarantees about the underlying representation of an `EnumSet`. To use
|
||||
/// them safely across FFI boundaries, the
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) attribute must be
|
||||
/// used with a primitive integer type. For example:
|
||||
///
|
||||
/// ```
|
||||
/// # use enumset::*;
|
||||
/// #
|
||||
/// # mod ffi_impl {
|
||||
/// # // This example “foreign” function is actually written in Rust, but for the sake
|
||||
/// # // of example, we'll pretend it's written in C.
|
||||
/// # #[no_mangle]
|
||||
/// # extern "C" fn some_foreign_function(set: u32) -> u32 {
|
||||
/// # set & 0b100
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// extern "C" {
|
||||
/// // This function is written in C like:
|
||||
/// // uint32_t some_foreign_function(uint32_t set) { … }
|
||||
/// fn some_foreign_function(set: EnumSet<MyEnum>) -> EnumSet<MyEnum>;
|
||||
/// }
|
||||
///
|
||||
/// #[derive(Debug, EnumSetType)]
|
||||
/// #[enumset(repr = "u32")]
|
||||
/// enum MyEnum { A, B, C }
|
||||
///
|
||||
/// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
|
||||
///
|
||||
/// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
|
||||
/// assert_eq!(new_set, enum_set!(MyEnum::C));
|
||||
/// ```
|
||||
///
|
||||
/// When an `EnumSet<T>` is received via FFI, all bits that don't correspond to an enum variant
|
||||
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(transparent)]
|
||||
pub struct EnumSet<T: EnumSetType> {
|
||||
pub(crate) repr: T::Repr,
|
||||
}
|
||||
|
||||
//region EnumSet operations
|
||||
impl<T: EnumSetType> EnumSet<T> {
|
||||
const EMPTY_REPR: Self = EnumSet { repr: T::Repr::EMPTY };
|
||||
const ALL_REPR: Self = EnumSet { repr: T::ALL_BITS };
|
||||
|
||||
/// Creates an empty `EnumSet`.
|
||||
#[inline(always)]
|
||||
pub const fn new() -> Self {
|
||||
Self::EMPTY_REPR
|
||||
}
|
||||
|
||||
/// Returns an `EnumSet` containing a single element.
|
||||
#[inline(always)]
|
||||
pub fn only(t: T) -> Self {
|
||||
let mut set = Self::new();
|
||||
set.insert(t);
|
||||
set
|
||||
}
|
||||
|
||||
/// Creates an empty `EnumSet`.
|
||||
///
|
||||
/// This is an alias for [`EnumSet::new`].
|
||||
#[inline(always)]
|
||||
pub const fn empty() -> Self {
|
||||
Self::EMPTY_REPR
|
||||
}
|
||||
|
||||
/// Returns an `EnumSet` containing all valid variants of the enum.
|
||||
#[inline(always)]
|
||||
pub const fn all() -> Self {
|
||||
Self::ALL_REPR
|
||||
}
|
||||
|
||||
/// Total number of bits used by this type. Note that the actual amount of space used is
|
||||
/// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
|
||||
///
|
||||
/// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
|
||||
/// (e.g. `enum Foo { A = 10, B = 20 }`)
|
||||
#[inline(always)]
|
||||
pub const fn bit_width() -> u32 {
|
||||
T::BIT_WIDTH
|
||||
}
|
||||
|
||||
/// The number of valid variants that this type can contain.
|
||||
///
|
||||
/// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
|
||||
/// (e.g. `enum Foo { A = 10, B = 20 }`)
|
||||
#[inline(always)]
|
||||
pub const fn variant_count() -> u32 {
|
||||
T::VARIANT_COUNT
|
||||
}
|
||||
|
||||
/// Returns the number of elements in this set.
|
||||
#[inline(always)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.repr.count_ones() as usize
|
||||
}
|
||||
/// Returns `true` if the set contains no elements.
|
||||
#[inline(always)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.repr.is_empty()
|
||||
}
|
||||
/// Removes all elements from the set.
|
||||
#[inline(always)]
|
||||
pub fn clear(&mut self) {
|
||||
self.repr = T::Repr::EMPTY;
|
||||
}
|
||||
|
||||
/// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
|
||||
/// checking for an empty intersection.
|
||||
#[inline(always)]
|
||||
pub fn is_disjoint(&self, other: Self) -> bool {
|
||||
(*self & other).is_empty()
|
||||
}
|
||||
/// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
|
||||
/// values in `other`.
|
||||
#[inline(always)]
|
||||
pub fn is_superset(&self, other: Self) -> bool {
|
||||
(*self & other).repr == other.repr
|
||||
}
|
||||
/// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
|
||||
/// the values in `self`.
|
||||
#[inline(always)]
|
||||
pub fn is_subset(&self, other: Self) -> bool {
|
||||
other.is_superset(*self)
|
||||
}
|
||||
|
||||
/// Returns a set containing any elements present in either set.
|
||||
#[inline(always)]
|
||||
pub fn union(&self, other: Self) -> Self {
|
||||
EnumSet { repr: self.repr | other.repr }
|
||||
}
|
||||
/// Returns a set containing every element present in both sets.
|
||||
#[inline(always)]
|
||||
pub fn intersection(&self, other: Self) -> Self {
|
||||
EnumSet { repr: self.repr & other.repr }
|
||||
}
|
||||
/// Returns a set containing element present in `self` but not in `other`.
|
||||
#[inline(always)]
|
||||
pub fn difference(&self, other: Self) -> Self {
|
||||
EnumSet { repr: self.repr.and_not(other.repr) }
|
||||
}
|
||||
/// Returns a set containing every element present in either `self` or `other`, but is not
|
||||
/// present in both.
|
||||
#[inline(always)]
|
||||
pub fn symmetrical_difference(&self, other: Self) -> Self {
|
||||
EnumSet { repr: self.repr ^ other.repr }
|
||||
}
|
||||
/// Returns a set containing all enum variants not in this set.
|
||||
#[inline(always)]
|
||||
pub fn complement(&self) -> Self {
|
||||
EnumSet { repr: !self.repr & T::ALL_BITS }
|
||||
}
|
||||
|
||||
/// Checks whether this set contains a value.
|
||||
#[inline(always)]
|
||||
pub fn contains(&self, value: T) -> bool {
|
||||
self.repr.has_bit(value.enum_into_u32())
|
||||
}
|
||||
|
||||
/// Adds a value to this set.
|
||||
///
|
||||
/// If the set did not have this value present, `true` is returned.
|
||||
///
|
||||
/// If the set did have this value present, `false` is returned.
|
||||
#[inline(always)]
|
||||
pub fn insert(&mut self, value: T) -> bool {
|
||||
let contains = !self.contains(value);
|
||||
self.repr.add_bit(value.enum_into_u32());
|
||||
contains
|
||||
}
|
||||
/// Removes a value from this set. Returns whether the value was present in the set.
|
||||
#[inline(always)]
|
||||
pub fn remove(&mut self, value: T) -> bool {
|
||||
let contains = self.contains(value);
|
||||
self.repr.remove_bit(value.enum_into_u32());
|
||||
contains
|
||||
}
|
||||
|
||||
/// Adds all elements in another set to this one.
|
||||
#[inline(always)]
|
||||
pub fn insert_all(&mut self, other: Self) {
|
||||
self.repr = self.repr | other.repr
|
||||
}
|
||||
/// Removes all values in another set from this one.
|
||||
#[inline(always)]
|
||||
pub fn remove_all(&mut self, other: Self) {
|
||||
self.repr = self.repr.and_not(other.repr);
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper type used for constant evaluation of enum operations.
|
||||
#[doc(hidden)]
|
||||
pub struct EnumSetInitHelper;
|
||||
impl EnumSetInitHelper {
|
||||
/// Just returns this value - the version for the enums themselves would wrap it into an
|
||||
/// enumset.
|
||||
pub const fn const_only<T>(&self, value: T) -> T {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
unsafe impl<T: EnumSetType> EnumSetConstHelper for EnumSet<T> {
|
||||
type ConstInitHelper = EnumSetInitHelper;
|
||||
const CONST_INIT_HELPER: Self::ConstInitHelper = EnumSetInitHelper;
|
||||
|
||||
type ConstOpHelper = T::ConstOpHelper;
|
||||
const CONST_OP_HELPER: Self::ConstOpHelper = T::CONST_OP_HELPER;
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> Default for EnumSet<T> {
|
||||
/// Returns an empty set.
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
|
||||
type Output = Self;
|
||||
#[inline(always)]
|
||||
fn sub(self, other: O) -> Self::Output {
|
||||
self.difference(other.into())
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
|
||||
type Output = Self;
|
||||
#[inline(always)]
|
||||
fn bitand(self, other: O) -> Self::Output {
|
||||
self.intersection(other.into())
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
|
||||
type Output = Self;
|
||||
#[inline(always)]
|
||||
fn bitor(self, other: O) -> Self::Output {
|
||||
self.union(other.into())
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
|
||||
type Output = Self;
|
||||
#[inline(always)]
|
||||
fn bitxor(self, other: O) -> Self::Output {
|
||||
self.symmetrical_difference(other.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
|
||||
#[inline(always)]
|
||||
fn sub_assign(&mut self, rhs: O) {
|
||||
*self = *self - rhs;
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
|
||||
#[inline(always)]
|
||||
fn bitand_assign(&mut self, rhs: O) {
|
||||
*self = *self & rhs;
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
|
||||
#[inline(always)]
|
||||
fn bitor_assign(&mut self, rhs: O) {
|
||||
*self = *self | rhs;
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
|
||||
#[inline(always)]
|
||||
fn bitxor_assign(&mut self, rhs: O) {
|
||||
*self = *self ^ rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> Not for EnumSet<T> {
|
||||
type Output = Self;
|
||||
#[inline(always)]
|
||||
fn not(self) -> Self::Output {
|
||||
self.complement()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> From<T> for EnumSet<T> {
|
||||
fn from(t: T) -> Self {
|
||||
EnumSet::only(t)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> PartialEq<T> for EnumSet<T> {
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.repr == EnumSet::only(*other).repr
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType + Debug> Debug for EnumSet<T> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
// Note: We don't use `.debug_struct` to avoid splitting lines when using `{:x}`
|
||||
f.write_str("EnumSet(")?;
|
||||
let mut i = self.iter();
|
||||
if let Some(v) = i.next() {
|
||||
v.fmt(f)?;
|
||||
for v in i {
|
||||
f.write_str(" | ")?;
|
||||
v.fmt(f)?;
|
||||
}
|
||||
}
|
||||
f.write_str(")")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType + Display> Display for EnumSet<T> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
let mut i = self.iter();
|
||||
if let Some(v) = i.next() {
|
||||
v.fmt(f)?;
|
||||
for v in i {
|
||||
f.write_str(" | ")?;
|
||||
v.fmt(f)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "defmt")]
|
||||
impl<T: EnumSetType + defmt::Format> defmt::Format for EnumSet<T> {
|
||||
fn format(&self, f: defmt::Formatter) {
|
||||
let mut i = self.iter();
|
||||
if let Some(v) = i.next() {
|
||||
defmt::write!(f, "{}", v);
|
||||
for v in i {
|
||||
defmt::write!(f, " | {}", v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::derived_hash_with_manual_eq)] // This impl exists to change trait bounds only.
|
||||
impl<T: EnumSetType> Hash for EnumSet<T> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.repr.hash(state)
|
||||
}
|
||||
}
|
||||
#[allow(clippy::non_canonical_partial_ord_impl)]
|
||||
impl<T: EnumSetType> PartialOrd for EnumSet<T> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
self.repr.partial_cmp(&other.repr)
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType> Ord for EnumSet<T> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.repr.cmp(&other.repr)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<T: EnumSetType> Serialize for EnumSet<T> {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
T::serialize(*self, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
T::deserialize(deserializer)
|
||||
}
|
||||
}
|
||||
//endregion
|
||||
|
||||
//region Deprecated functions
|
||||
/// This impl contains all outdated or deprecated functions.
|
||||
impl<T: EnumSetType> EnumSet<T> {
|
||||
/// An empty `EnumSet`.
|
||||
///
|
||||
/// This is deprecated because [`EnumSet::empty`] is now `const`.
|
||||
#[deprecated = "Use `EnumSet::empty()` instead."]
|
||||
pub const EMPTY: Self = Self::EMPTY_REPR;
|
||||
|
||||
/// An `EnumSet` containing all valid variants of the enum.
|
||||
///
|
||||
/// This is deprecated because [`EnumSet::all`] is now `const`.
|
||||
#[deprecated = "Use `EnumSet::all()` instead."]
|
||||
pub const ALL: Self = Self::ALL_REPR;
|
||||
}
|
||||
//endregion
|
||||
|
||||
//region EnumSet conversions
|
||||
impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> {
|
||||
/// Returns a `T::Repr` representing the elements of this set.
|
||||
///
|
||||
/// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
|
||||
/// panic or truncate any bits.
|
||||
///
|
||||
/// In order to use this method, the definition of `T` must have an
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
|
||||
/// with a primitive integer type.
|
||||
#[inline(always)]
|
||||
pub const fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr {
|
||||
self.repr
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `T::Repr` without checking for invalid bits.
|
||||
///
|
||||
/// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
|
||||
/// panic or truncate any bits, provided the conditions under “Safety” are upheld.
|
||||
///
|
||||
/// In order to use this method, the definition of `T` must have an
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
|
||||
/// with a primitive integer type.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// All bits in the provided parameter `bits` that don't correspond to an enum variant of
|
||||
/// `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
|
||||
#[inline(always)]
|
||||
pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
|
||||
Self { repr: bits }
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `T::Repr`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this
|
||||
/// method will panic.
|
||||
///
|
||||
/// In order to use this method, the definition of `T` must have an
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
|
||||
/// with a primitive integer type.
|
||||
#[inline(always)]
|
||||
pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
|
||||
Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
|
||||
}
|
||||
|
||||
/// Attempts to constructs a bitset from a `T::Repr`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this
|
||||
/// method will return `None`.
|
||||
///
|
||||
/// In order to use this method, the definition of `T` must have an
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
|
||||
/// with a primitive integer type.
|
||||
#[inline(always)]
|
||||
pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> {
|
||||
let mask = Self::all().repr;
|
||||
if bits.and_not(mask).is_empty() {
|
||||
Some(EnumSet { repr: bits })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
|
||||
///
|
||||
/// In order to use this method, the definition of `T` must have an
|
||||
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
|
||||
/// with a primitive integer type.
|
||||
#[inline(always)]
|
||||
pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
|
||||
let mask = Self::all().as_repr();
|
||||
let bits = bits & mask;
|
||||
EnumSet { repr: bits }
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper macro for generating conversion functions.
|
||||
macro_rules! conversion_impls {
|
||||
(
|
||||
$(for_num!(
|
||||
$underlying:ty, $underlying_str:expr,
|
||||
$from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
|
||||
$from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident,
|
||||
$to:ident $try_to:ident $to_truncated:ident
|
||||
);)*
|
||||
) => {
|
||||
impl<T: EnumSetType> EnumSet<T> {$(
|
||||
#[doc = "Returns a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
|
||||
not fit in a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`, this method will panic."]
|
||||
#[inline(always)]
|
||||
pub fn $to(&self) -> $underlying {
|
||||
self.$try_to().expect("Bitset will not fit into this type.")
|
||||
}
|
||||
|
||||
#[doc = "Tries to return a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
|
||||
not fit in a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`, this method will panic."]
|
||||
#[inline(always)]
|
||||
pub fn $try_to(&self) -> Option<$underlying> {
|
||||
EnumSetTypeRepr::$to_fn_opt(&self.repr)
|
||||
}
|
||||
|
||||
#[doc = "Returns a truncated `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
|
||||
not fit in a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`, this method will truncate any bits that don't fit."]
|
||||
#[inline(always)]
|
||||
pub fn $to_truncated(&self) -> $underlying {
|
||||
EnumSetTypeRepr::$to_fn(&self.repr)
|
||||
}
|
||||
|
||||
#[doc = "Constructs a bitset from a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
|
||||
method will panic."]
|
||||
#[inline(always)]
|
||||
pub fn $from(bits: $underlying) -> Self {
|
||||
Self::$try_from(bits).expect("Bitset contains invalid variants.")
|
||||
}
|
||||
|
||||
#[doc = "Attempts to constructs a bitset from a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
|
||||
method will return `None`."]
|
||||
#[inline(always)]
|
||||
pub fn $try_from(bits: $underlying) -> Option<Self> {
|
||||
let bits = T::Repr::$from_fn_opt(bits);
|
||||
let mask = T::ALL_BITS;
|
||||
bits.and_then(|bits| if bits.and_not(mask).is_empty() {
|
||||
Some(EnumSet { repr: bits })
|
||||
} else {
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
#[doc = "Constructs a bitset from a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`, ignoring bits that do not correspond to a variant."]
|
||||
#[inline(always)]
|
||||
pub fn $from_truncated(bits: $underlying) -> Self {
|
||||
let mask = Self::all().$to_truncated();
|
||||
let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
|
||||
EnumSet { repr: bits }
|
||||
}
|
||||
|
||||
#[doc = "Constructs a bitset from a `"]
|
||||
#[doc = $underlying_str]
|
||||
#[doc = "`, without checking for invalid bits."]
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
|
||||
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
|
||||
/// to `1`.
|
||||
#[inline(always)]
|
||||
pub unsafe fn $from_unchecked(bits: $underlying) -> Self {
|
||||
EnumSet { repr: <T::Repr as EnumSetTypeRepr>::$from_fn(bits) }
|
||||
}
|
||||
)*}
|
||||
}
|
||||
}
|
||||
conversion_impls! {
|
||||
for_num!(u8, "u8",
|
||||
from_u8 to_u8 from_u8_opt to_u8_opt,
|
||||
from_u8 try_from_u8 from_u8_truncated from_u8_unchecked,
|
||||
as_u8 try_as_u8 as_u8_truncated);
|
||||
for_num!(u16, "u16",
|
||||
from_u16 to_u16 from_u16_opt to_u16_opt,
|
||||
from_u16 try_from_u16 from_u16_truncated from_u16_unchecked,
|
||||
as_u16 try_as_u16 as_u16_truncated);
|
||||
for_num!(u32, "u32",
|
||||
from_u32 to_u32 from_u32_opt to_u32_opt,
|
||||
from_u32 try_from_u32 from_u32_truncated from_u32_unchecked,
|
||||
as_u32 try_as_u32 as_u32_truncated);
|
||||
for_num!(u64, "u64",
|
||||
from_u64 to_u64 from_u64_opt to_u64_opt,
|
||||
from_u64 try_from_u64 from_u64_truncated from_u64_unchecked,
|
||||
as_u64 try_as_u64 as_u64_truncated);
|
||||
for_num!(u128, "u128",
|
||||
from_u128 to_u128 from_u128_opt to_u128_opt,
|
||||
from_u128 try_from_u128 from_u128_truncated from_u128_unchecked,
|
||||
as_u128 try_as_u128 as_u128_truncated);
|
||||
for_num!(usize, "usize",
|
||||
from_usize to_usize from_usize_opt to_usize_opt,
|
||||
from_usize try_from_usize from_usize_truncated from_usize_unchecked,
|
||||
as_usize try_as_usize as_usize_truncated);
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> EnumSet<T> {
|
||||
/// Returns an `[u64; O]` representing the elements of this set.
|
||||
///
|
||||
/// If the underlying bitset will not fit in a `[u64; O]`, this method will panic.
|
||||
pub fn as_array<const O: usize>(&self) -> [u64; O] {
|
||||
self.try_as_array()
|
||||
.expect("Bitset will not fit into this type.")
|
||||
}
|
||||
|
||||
/// Returns an `[u64; O]` representing the elements of this set.
|
||||
///
|
||||
/// If the underlying bitset will not fit in a `[u64; O]`, this method will instead return
|
||||
/// `None`.
|
||||
pub fn try_as_array<const O: usize>(&self) -> Option<[u64; O]> {
|
||||
self.repr.to_u64_array_opt()
|
||||
}
|
||||
|
||||
/// Returns an `[u64; O]` representing the elements of this set.
|
||||
///
|
||||
/// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits
|
||||
/// that don't fit.
|
||||
pub fn as_array_truncated<const O: usize>(&self) -> [u64; O] {
|
||||
self.repr.to_u64_array()
|
||||
}
|
||||
|
||||
/// Attempts to constructs a bitset from a `[u64; O]`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this method will panic.
|
||||
pub fn from_array<const O: usize>(v: [u64; O]) -> Self {
|
||||
Self::try_from_array(v).expect("Bitset contains invalid variants.")
|
||||
}
|
||||
|
||||
/// Attempts to constructs a bitset from a `[u64; O]`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
|
||||
pub fn try_from_array<const O: usize>(bits: [u64; O]) -> Option<Self> {
|
||||
let bits = T::Repr::from_u64_array_opt::<O>(bits);
|
||||
let mask = T::ALL_BITS;
|
||||
bits.and_then(|bits| {
|
||||
if bits.and_not(mask).is_empty() {
|
||||
Some(EnumSet { repr: bits })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant.
|
||||
pub fn from_array_truncated<const O: usize>(bits: [u64; O]) -> Self {
|
||||
let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS;
|
||||
EnumSet { repr: bits }
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `[u64; O]`, without checking for invalid bits.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
|
||||
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
|
||||
/// to `1`.
|
||||
#[inline(always)]
|
||||
pub unsafe fn from_array_unchecked<const O: usize>(bits: [u64; O]) -> Self {
|
||||
EnumSet { repr: T::Repr::from_u64_array(bits) }
|
||||
}
|
||||
|
||||
/// Returns a `Vec<u64>` representing the elements of this set.
|
||||
#[cfg(feature = "alloc")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
|
||||
pub fn to_vec(&self) -> alloc::vec::Vec<u64> {
|
||||
let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN];
|
||||
self.repr.to_u64_slice(&mut vec);
|
||||
vec
|
||||
}
|
||||
|
||||
/// Copies the elements of this set into a `&mut [u64]`.
|
||||
///
|
||||
/// If the underlying bitset will not fit in the provided slice, this method will panic.
|
||||
pub fn copy_into_slice(&self, data: &mut [u64]) {
|
||||
self.try_copy_into_slice(data)
|
||||
.expect("Bitset will not fit into slice.")
|
||||
}
|
||||
|
||||
/// Copies the elements of this set into a `&mut [u64]`.
|
||||
///
|
||||
/// If the underlying bitset will not fit in the provided slice, this method will return
|
||||
/// `None`. Otherwise, it will return `Some(())`.
|
||||
#[must_use]
|
||||
pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> {
|
||||
self.repr.to_u64_slice_opt(data)
|
||||
}
|
||||
|
||||
/// Copies the elements of this set into a `&mut [u64]`.
|
||||
///
|
||||
/// If the underlying bitset will not fit in the provided slice, this method will truncate any
|
||||
/// bits that don't fit.
|
||||
pub fn copy_into_slice_truncated(&self, data: &mut [u64]) {
|
||||
self.repr.to_u64_slice(data)
|
||||
}
|
||||
|
||||
/// Attempts to constructs a bitset from a `&[u64]`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this method will panic.
|
||||
pub fn from_slice(v: &[u64]) -> Self {
|
||||
Self::try_from_slice(v).expect("Bitset contains invalid variants.")
|
||||
}
|
||||
|
||||
/// Attempts to constructs a bitset from a `&[u64]`.
|
||||
///
|
||||
/// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
|
||||
pub fn try_from_slice(bits: &[u64]) -> Option<Self> {
|
||||
let bits = T::Repr::from_u64_slice_opt(bits);
|
||||
let mask = T::ALL_BITS;
|
||||
bits.and_then(|bits| {
|
||||
if bits.and_not(mask).is_empty() {
|
||||
Some(EnumSet { repr: bits })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant.
|
||||
pub fn from_slice_truncated(bits: &[u64]) -> Self {
|
||||
let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS;
|
||||
EnumSet { repr: bits }
|
||||
}
|
||||
|
||||
/// Constructs a bitset from a `&[u64]`, without checking for invalid bits.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
|
||||
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
|
||||
/// to `1`.
|
||||
#[inline(always)]
|
||||
pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self {
|
||||
EnumSet { repr: T::Repr::from_u64_slice(bits) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType, const N: usize> From<[T; N]> for EnumSet<T> {
|
||||
fn from(value: [T; N]) -> Self {
|
||||
let mut new = EnumSet::new();
|
||||
for elem in value {
|
||||
new.insert(elem);
|
||||
}
|
||||
new
|
||||
}
|
||||
}
|
||||
//endregion
|
||||
|
||||
//region EnumSet iter
|
||||
/// The iterator used by [`EnumSet`]s.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EnumSetIter<T: EnumSetType> {
|
||||
iter: <T::Repr as EnumSetTypeRepr>::Iter,
|
||||
}
|
||||
impl<T: EnumSetType> EnumSetIter<T> {
|
||||
fn new(set: EnumSet<T>) -> EnumSetIter<T> {
|
||||
EnumSetIter { iter: set.repr.iter() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> EnumSet<T> {
|
||||
/// Iterates the contents of the set in order from the least significant bit to the most
|
||||
/// significant bit.
|
||||
///
|
||||
/// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
|
||||
/// rather than holding a reference to it.
|
||||
pub fn iter(&self) -> EnumSetIter<T> {
|
||||
EnumSetIter::new(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> Iterator for EnumSetIter<T> {
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter
|
||||
.next()
|
||||
.map(|x| unsafe { T::enum_from_u32_checked(x) })
|
||||
}
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
self.iter
|
||||
.next_back()
|
||||
.map(|x| unsafe { T::enum_from_u32_checked(x) })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
|
||||
|
||||
impl<T: EnumSetType> Extend<T> for EnumSet<T> {
|
||||
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
|
||||
iter.into_iter().for_each(|v| {
|
||||
self.insert(v);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: EnumSetType> Extend<&'a T> for EnumSet<T> {
|
||||
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
|
||||
iter.into_iter().for_each(|v| {
|
||||
self.insert(*v);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
|
||||
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
|
||||
let mut set = EnumSet::default();
|
||||
set.extend(iter);
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
|
||||
fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
|
||||
iter.into_iter().for_each(|v| {
|
||||
self.insert_all(v);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: EnumSetType> Extend<&'a EnumSet<T>> for EnumSet<T> {
|
||||
fn extend<I: IntoIterator<Item = &'a EnumSet<T>>>(&mut self, iter: I) {
|
||||
iter.into_iter().for_each(|v| {
|
||||
self.insert_all(*v);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
|
||||
fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
|
||||
let mut set = EnumSet::default();
|
||||
set.extend(iter);
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EnumSetType> IntoIterator for EnumSet<T> {
|
||||
type Item = T;
|
||||
type IntoIter = EnumSetIter<T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType> Sum for EnumSet<T> {
|
||||
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
|
||||
iter.fold(EnumSet::empty(), |a, v| a | v)
|
||||
}
|
||||
}
|
||||
impl<'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
|
||||
fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
|
||||
iter.fold(EnumSet::empty(), |a, v| a | *v)
|
||||
}
|
||||
}
|
||||
impl<T: EnumSetType> Sum<T> for EnumSet<T> {
|
||||
fn sum<I: Iterator<Item = T>>(iter: I) -> Self {
|
||||
iter.fold(EnumSet::empty(), |a, v| a | v)
|
||||
}
|
||||
}
|
||||
impl<'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
|
||||
fn sum<I: Iterator<Item = &'a T>>(iter: I) -> Self {
|
||||
iter.fold(EnumSet::empty(), |a, v| a | *v)
|
||||
}
|
||||
}
|
||||
//endregion
|
||||
Vendored
+82
@@ -0,0 +1,82 @@
|
||||
use crate::repr::EnumSetTypeRepr;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use crate::EnumSet;
|
||||
|
||||
/// The trait used to define enum types that may be used with [`EnumSet`].
|
||||
///
|
||||
/// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
|
||||
/// internal structure may change at any time with no warning.
|
||||
///
|
||||
/// For full documentation on the procedural derive and its options, see
|
||||
/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType).
|
||||
///
|
||||
/// [`EnumSet`]: crate::set::EnumSet
|
||||
pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {}
|
||||
|
||||
/// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
|
||||
///
|
||||
/// An implementation of this trait is generated by using
|
||||
/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType) with the annotation
|
||||
/// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`.
|
||||
///
|
||||
/// For any type `T` that implements this trait, the in-memory representation of `EnumSet<T>`
|
||||
/// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation
|
||||
/// under “FFI, Safety and `repr`”][crate::set::EnumSet#ffi-safety-and-repr] for an example.
|
||||
///
|
||||
/// [`EnumSet`]: crate::set::EnumSet
|
||||
pub unsafe trait EnumSetTypeWithRepr:
|
||||
EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr>
|
||||
{
|
||||
/// The guaranteed representation.
|
||||
type Repr: EnumSetTypeRepr;
|
||||
}
|
||||
|
||||
/// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
|
||||
pub unsafe trait EnumSetTypePrivate: EnumSetConstHelper + Sized {
|
||||
/// The underlying type used to store the bitset.
|
||||
type Repr: EnumSetTypeRepr;
|
||||
/// A mask of bits that are valid in the bitset.
|
||||
const ALL_BITS: Self::Repr;
|
||||
/// The largest bit used in the bitset.
|
||||
const BIT_WIDTH: u32;
|
||||
/// The number of variants in the bitset.
|
||||
const VARIANT_COUNT: u32;
|
||||
|
||||
/// Converts an enum of this type into its bit position.
|
||||
fn enum_into_u32(self) -> u32;
|
||||
|
||||
/// Converts a bit position into an enum value.
|
||||
unsafe fn enum_from_u32(val: u32) -> Self;
|
||||
|
||||
/// Converts a bit position into an enum value, with an debug_assert.
|
||||
unsafe fn enum_from_u32_checked(val: u32) -> Self {
|
||||
debug_assert!(Self::ALL_BITS.has_bit(val), "Unknown bit retrieved from bitset.");
|
||||
Self::enum_from_u32(val)
|
||||
}
|
||||
|
||||
/// Serializes the `EnumSet`.
|
||||
///
|
||||
/// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
|
||||
/// can control how `EnumSet` is serialized.
|
||||
#[cfg(feature = "serde")]
|
||||
fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
|
||||
where Self: EnumSetType;
|
||||
/// Deserializes the `EnumSet`.
|
||||
#[cfg(feature = "serde")]
|
||||
fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
|
||||
where Self: EnumSetType;
|
||||
}
|
||||
|
||||
/// Retrieves a helper type for constant time operations on `EnumSet`s.
|
||||
pub unsafe trait EnumSetConstHelper {
|
||||
/// A helper type used to convert values to EnumSets at compile-time.
|
||||
type ConstInitHelper;
|
||||
/// The instance of the `ConstInitHelper`.
|
||||
const CONST_INIT_HELPER: Self::ConstInitHelper;
|
||||
|
||||
/// A helper type used to implement compile-time operations on enums.
|
||||
type ConstOpHelper;
|
||||
/// The instance of the `ConstOpHelper`.
|
||||
const CONST_OP_HELPER: Self::ConstOpHelper;
|
||||
}
|
||||
+729
@@ -0,0 +1,729 @@
|
||||
#![allow(dead_code)]
|
||||
#![deny(warnings)]
|
||||
|
||||
use enumset::*;
|
||||
use std::collections::{HashSet, BTreeSet};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
|
||||
/// Used to test the degenerate case of an uninhabited enum.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum EmptyEnum { }
|
||||
|
||||
// Test of a relatively typical enum.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
enum SmallEnum {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
// Used to test enums where the required impls are derived manually.
|
||||
#[derive(Clone, Copy, Debug, EnumSetType, Eq, PartialEq)]
|
||||
#[enumset(no_super_impls)]
|
||||
enum SmallEnumExplicitDerive {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
// Used to test very large enums.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "u128")]
|
||||
pub enum LargeEnum {
|
||||
_00, _01, _02, _03, _04, _05, _06, _07,
|
||||
_10, _11, _12, _13, _14, _15, _16, _17,
|
||||
_20, _21, _22, _23, _24, _25, _26, _27,
|
||||
_30, _31, _32, _33, _34, _35, _36, _37,
|
||||
_40, _41, _42, _43, _44, _45, _46, _47,
|
||||
_50, _51, _52, _53, _54, _55, _56, _57,
|
||||
_60, _61, _62, _63, _64, _65, _66, _67,
|
||||
_70, _71, _72, _73, _74, _75, _76, _77,
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test enums with sparse elements.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum SparseEnum {
|
||||
A = 0xA, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80,
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum with a single element.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum1 {
|
||||
A,
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum with eight variants (exactly fits in an u8)
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum8 {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum with 128 variants (exactly fits in an u128)
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum128 {
|
||||
A, B, C, D, E, F, G, H, _8, _9, _10, _11, _12, _13, _14, _15,
|
||||
_16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31,
|
||||
_32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47,
|
||||
_48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63,
|
||||
_64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79,
|
||||
_80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95,
|
||||
_96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109,
|
||||
_110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122,
|
||||
_123, _124, _125, _126, _127,
|
||||
}
|
||||
|
||||
/// Used to test repr on enums.
|
||||
#[repr(u32)]
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum ReprEnum {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test repr on enums. (cont)
|
||||
#[rustversion::attr(since(1.89), repr(u128))]
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum ReprEnum2 {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test repr on enums. (cont)
|
||||
#[repr(isize)]
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum ReprEnum3 {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test repr on enums. (cont)
|
||||
#[repr(C)]
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum ReprEnum4 {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test massive enums that require arrays to use.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum GiantEnum {
|
||||
A = 100, B = 200, C = 300, D = 400, E = 500, F = 600, G = 700, H = 800,
|
||||
}
|
||||
|
||||
/// Used to test enums that are explicitly forced to use the array representation.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "array")]
|
||||
pub enum SmallArrayEnum {
|
||||
A, B, C, D, E, F, G, H
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum exactly one bit larger than a single u64 word
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "array")]
|
||||
pub enum MarginalArrayEnumS2 {
|
||||
A, B, C, D, E, F, G, H, Marginal = 64,
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum that requires two u64 words.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "array")]
|
||||
pub enum MarginalArrayEnumS2H {
|
||||
A = 64, B, C, D, E, F, G, H, Marginal = 127,
|
||||
}
|
||||
|
||||
/// Used to test the edge case of an enum that requires one more bit than two u64 words.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "array")]
|
||||
pub enum MarginalArrayEnumS3 {
|
||||
A, B, C, D, E, F, G, H, Marginal = 128,
|
||||
}
|
||||
|
||||
/// Used to test enums with sparse elements.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(map = "compact")]
|
||||
pub enum CompactEnumA {
|
||||
A = 0xA, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80,
|
||||
}
|
||||
|
||||
/// Used to test enums with sparse elements.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(map = "compact", repr = "u8")]
|
||||
#[repr(i64)]
|
||||
pub enum CompactEnumB {
|
||||
A = 2, B = 4, C = 6, D = 8, E = -10, F = 120, G = -180, H = (1 << 60) | 12345,
|
||||
}
|
||||
|
||||
/// Used to test MSB.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "u64", map = "msb")]
|
||||
pub enum MsbEnum {
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
|
||||
/// Used to test MSB.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "u64", map = "msb")]
|
||||
enum MsbSparseEnum {
|
||||
A = 0xA, B = 15, C = 22, D = 42, E = 55, F, G, H,
|
||||
}
|
||||
|
||||
/// Used to test massive enums that require arrays to use.
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(map = "mask")]
|
||||
pub enum MaskEnum {
|
||||
A = 0x1, B = 0x2, C = 0x4, D = 0x8, E = 0x10, F = 0x20, G = 0x40, H = 0x80,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(map = "mask")]
|
||||
pub enum MaskSparseEnum {
|
||||
A = 1 << 0, B = 1 << 3, C = 1 << 4, D = 1 << 8,
|
||||
E = 1 << 9, F = 1 << 30, G = 1 << 33, H = 1 << 62,
|
||||
}
|
||||
|
||||
/// Tests that all variants are properly present when `EnumSet::all` is used.
|
||||
macro_rules! test_variants {
|
||||
($enum_name:ident $all_empty_test:ident $($variant:ident,)*) => {
|
||||
#[test]
|
||||
fn $all_empty_test() {
|
||||
let all = EnumSet::<$enum_name>::all();
|
||||
let empty = EnumSet::<$enum_name>::empty();
|
||||
|
||||
$(
|
||||
assert!(!empty.contains($enum_name::$variant));
|
||||
assert!(all.contains($enum_name::$variant));
|
||||
)*
|
||||
}
|
||||
}
|
||||
}
|
||||
test_variants! { SmallEnum small_enum_all_empty
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
test_variants! { SmallEnumExplicitDerive small_enum_explicit_derive_all_empty
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
test_variants! { LargeEnum large_enum_all_empty
|
||||
_00, _01, _02, _03, _04, _05, _06, _07,
|
||||
_10, _11, _12, _13, _14, _15, _16, _17,
|
||||
_20, _21, _22, _23, _24, _25, _26, _27,
|
||||
_30, _31, _32, _33, _34, _35, _36, _37,
|
||||
_40, _41, _42, _43, _44, _45, _46, _47,
|
||||
_50, _51, _52, _53, _54, _55, _56, _57,
|
||||
_60, _61, _62, _63, _64, _65, _66, _67,
|
||||
_70, _71, _72, _73, _74, _75, _76, _77,
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
}
|
||||
test_variants! { SparseEnum sparse_enum_all_empty
|
||||
A, B, C, D, E, F, G,
|
||||
}
|
||||
test_variants! { CompactEnumA compact_enum_a_all_empty
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
test_variants! { CompactEnumB compact_enum_b_all_empty
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
macro_rules! test_enum {
|
||||
($e:ident, $mem_size:expr, ordered) => {
|
||||
test_enum!($e, $mem_size);
|
||||
|
||||
/// Basic test that `Debug` returns the expected outupt.
|
||||
#[test]
|
||||
fn debug_impl_has_expected_output() {
|
||||
assert_eq!(format!("{:?}", $e::A | $e::B | $e::D), "EnumSet(A | B | D)");
|
||||
}
|
||||
|
||||
/// Tests that the iterator returns enums in the expected order.
|
||||
#[test]
|
||||
fn iter_ordering() {
|
||||
let set_a = $e::A | $e::B | $e::E;
|
||||
let vec_a: Vec<_> = set_a.iter().collect();
|
||||
assert_eq!(vec_a, &[$e::A, $e::B, $e::E]);
|
||||
let vec_a_rev: Vec<_> = set_a.iter().rev().collect();
|
||||
assert_eq!(vec_a_rev, &[$e::E, $e::B, $e::A]);
|
||||
|
||||
let set_b = $e::B | $e::C | $e::D | $e::G;
|
||||
let vec_b: Vec<_> = set_b.iter().collect();
|
||||
assert_eq!(vec_b, &[$e::B, $e::C, $e::D, $e::G]);
|
||||
let vec_b_rev: Vec<_> = set_b.iter().rev().collect();
|
||||
assert_eq!(vec_b_rev, &[$e::G, $e::D, $e::C, $e::B]);
|
||||
}
|
||||
|
||||
/// Checks that mixing next and next_back works properly.
|
||||
#[test]
|
||||
fn iter_both_ends() {
|
||||
{
|
||||
let e1 = $e::A | $e::B | $e::C | $e::D | $e::E | $e::F | $e::G;
|
||||
let mut iter = e1.iter();
|
||||
assert_eq!(iter.next(), Some($e::A));
|
||||
assert_eq!(iter.next(), Some($e::B));
|
||||
assert_eq!(iter.next_back(), Some($e::G));
|
||||
assert_eq!(iter.next_back(), Some($e::F));
|
||||
assert_eq!(iter.next(), Some($e::C));
|
||||
assert_eq!(iter.next_back(), Some($e::E));
|
||||
assert_eq!(iter.next(), Some($e::D));
|
||||
assert_eq!(iter.next(), None);
|
||||
assert_eq!(iter.next(), None);
|
||||
assert_eq!(iter.next_back(), None);
|
||||
}
|
||||
|
||||
{
|
||||
let e1 = $e::A | $e::B | $e::C | $e::F | $e::G;
|
||||
let mut iter = e1.iter();
|
||||
assert_eq!(iter.next_back(), Some($e::G));
|
||||
assert_eq!(iter.next(), Some($e::A));
|
||||
assert_eq!(iter.next_back(), Some($e::F));
|
||||
assert_eq!(iter.next_back(), Some($e::C));
|
||||
assert_eq!(iter.next(), Some($e::B));
|
||||
assert_eq!(iter.next_back(), None);
|
||||
assert_eq!(iter.next(), None);
|
||||
assert_eq!(iter.next_back(), None);
|
||||
}
|
||||
}
|
||||
};
|
||||
($e:ident, $mem_size:expr) => {
|
||||
const CONST_SET: EnumSet<$e> = enum_set!($e::A | $e::C);
|
||||
|
||||
/// Tests that sets created at compiletime using const exprs work as expected.
|
||||
#[test]
|
||||
fn const_set() {
|
||||
const CONST_1_SET: EnumSet<$e> = enum_set!($e::A);
|
||||
const CONST_SET_CHAIN: EnumSet<$e> = enum_set!(CONST_SET | $e::D);
|
||||
const CONST_SET_CHAIN_2: EnumSet<$e> = enum_set!($e::E | CONST_SET);
|
||||
const CONST_SET_CHAIN_3: EnumSet<$e> = enum_set!(CONST_SET_CHAIN | CONST_SET_CHAIN_2);
|
||||
const CONST_UNION: EnumSet<$e> = enum_set_union!(CONST_SET_CHAIN, CONST_SET_CHAIN_2);
|
||||
const CONST_INTERSECTION: EnumSet<$e> = enum_set_intersection!(CONST_SET_CHAIN, CONST_SET_CHAIN_2);
|
||||
const CONST_DIFFERENCE: EnumSet<$e> = enum_set_difference!(CONST_UNION, CONST_SET);
|
||||
const CONST_COMPLEMENT: EnumSet<$e> = enum_set_complement!(CONST_SET);
|
||||
const CONST_SYMMETRIC_DIFFERENCE: EnumSet<$e> = enum_set_symmetric_difference!(CONST_SET_CHAIN, CONST_SET_CHAIN_2);
|
||||
const EMPTY_SET: EnumSet<$e> = EnumSet::empty();
|
||||
const ALL_SET: EnumSet<$e> = EnumSet::all();
|
||||
const VARIANT_COUNT: usize = EnumSet::<$e>::variant_count() as usize;
|
||||
|
||||
assert_eq!(CONST_SET, $e::A | $e::C);
|
||||
assert_eq!(CONST_1_SET, $e::A);
|
||||
assert_eq!(CONST_SET_CHAIN, $e::A | $e::C | $e::D);
|
||||
assert_eq!(CONST_SET_CHAIN_2, $e::A | $e::C | $e::E);
|
||||
assert_eq!(CONST_SET_CHAIN_3, $e::A | $e::C | $e::D | $e::E);
|
||||
assert_eq!(CONST_UNION, $e::A | $e::C | $e::D | $e::E);
|
||||
assert_eq!(CONST_INTERSECTION, $e::A | $e::C);
|
||||
assert_eq!(CONST_COMPLEMENT, !($e::A | $e::C));
|
||||
assert_eq!(CONST_SYMMETRIC_DIFFERENCE, $e::D | $e::E);
|
||||
|
||||
assert!(EMPTY_SET.is_empty());
|
||||
assert_eq!(ALL_SET.len(), VARIANT_COUNT);
|
||||
assert_eq!(ALL_SET, EnumSet::all());
|
||||
}
|
||||
|
||||
/// Tests that enumsets work in match expressions.
|
||||
#[test]
|
||||
fn match_const_test() {
|
||||
match CONST_SET {
|
||||
CONST_SET => { /* ok */ }
|
||||
_ => panic!("match fell through?"),
|
||||
}
|
||||
}
|
||||
|
||||
// Basic tests to ensure insert/remove operations work properly.
|
||||
#[test]
|
||||
fn basic_add_remove() {
|
||||
let mut set = EnumSet::new();
|
||||
set.insert($e::A);
|
||||
set.insert($e::B);
|
||||
set.insert($e::C);
|
||||
assert_eq!(set, $e::A | $e::B | $e::C);
|
||||
set.remove($e::B);
|
||||
assert_eq!(set, $e::A | $e::C);
|
||||
set.insert($e::D);
|
||||
assert_eq!(set, $e::A | $e::C | $e::D);
|
||||
set.insert_all($e::F | $e::E | $e::G);
|
||||
assert_eq!(set, $e::A | $e::C | $e::D | $e::F | $e::E | $e::G);
|
||||
set.remove_all($e::A | $e::D | $e::G);
|
||||
assert_eq!(set, $e::C | $e::F | $e::E);
|
||||
assert!(!set.is_empty());
|
||||
set.clear();
|
||||
assert!(set.is_empty());
|
||||
}
|
||||
|
||||
/// Basic tests to ensure the return status for `insert` is correct.
|
||||
#[test]
|
||||
fn already_present_element() {
|
||||
let mut set = EnumSet::new();
|
||||
assert!(set.insert($e::A));
|
||||
assert!(!set.insert($e::A));
|
||||
set.remove($e::A);
|
||||
assert!(set.insert($e::A));
|
||||
}
|
||||
|
||||
/// Basic test to ensure `empty` actually returns an empty set.
|
||||
#[test]
|
||||
fn empty_is_empty() {
|
||||
assert_eq!(EnumSet::<$e>::empty().len(), 0)
|
||||
}
|
||||
|
||||
/// Basic test to ensure that the length of the complete set is as expected.
|
||||
#[test]
|
||||
fn all_len() {
|
||||
assert_eq!(EnumSet::<$e>::all().len(), EnumSet::<$e>::variant_count() as usize)
|
||||
}
|
||||
|
||||
/// Tests the basic functionality of the iterator tyep.
|
||||
#[test]
|
||||
fn iter_basic_ops() {
|
||||
let mut set = EnumSet::new();
|
||||
set.insert($e::A);
|
||||
set.insert($e::B);
|
||||
set.extend($e::C | $e::E);
|
||||
|
||||
let mut set_2 = EnumSet::new();
|
||||
let vec: Vec<_> = set.iter().collect();
|
||||
for val in vec {
|
||||
assert!(!set_2.contains(val));
|
||||
set_2.insert(val);
|
||||
}
|
||||
assert_eq!(set, set_2);
|
||||
|
||||
let mut set_3 = EnumSet::new();
|
||||
for val in set {
|
||||
assert!(!set_3.contains(val));
|
||||
set_3.insert(val);
|
||||
}
|
||||
assert_eq!(set, set_3);
|
||||
|
||||
let mut set_4 = EnumSet::new();
|
||||
let vec: EnumSet<_> = set.into_iter().map(EnumSet::only).collect();
|
||||
for val in vec {
|
||||
assert!(!set_4.contains(val));
|
||||
set_4.insert(val);
|
||||
}
|
||||
assert_eq!(set, set_4);
|
||||
|
||||
let mut set_5 = EnumSet::new();
|
||||
let vec: EnumSet<_> = set.iter().collect();
|
||||
for val in vec {
|
||||
assert!(!set_5.contains(val));
|
||||
set_5.insert(val);
|
||||
}
|
||||
assert_eq!(set, set_5);
|
||||
}
|
||||
|
||||
/// Tests that iteration on an empty seti n fact returns nothing.
|
||||
#[test]
|
||||
fn empty_iter() {
|
||||
for _ in EnumSet::<$e>::new() {
|
||||
panic!("should not happen");
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests that the size hint returned by the iterator is correct.
|
||||
#[test]
|
||||
fn iter_size_hint() {
|
||||
fn check_iter_size_hint(set: EnumSet<$e>) {
|
||||
let count = set.len();
|
||||
|
||||
// check for forward iteration
|
||||
{
|
||||
let mut itr = set.iter();
|
||||
for idx in 0 .. count {
|
||||
assert_eq!(itr.size_hint(), (count-idx, Some(count-idx)));
|
||||
assert_eq!(itr.len(), count-idx);
|
||||
assert!(itr.next().is_some());
|
||||
}
|
||||
assert_eq!(itr.size_hint(), (0, Some(0)));
|
||||
assert_eq!(itr.len(), 0);
|
||||
}
|
||||
|
||||
// check for backwards iteration
|
||||
{
|
||||
let mut itr = set.iter().rev();
|
||||
for idx in 0 .. count {
|
||||
assert_eq!(itr.size_hint(), (count-idx, Some(count-idx)));
|
||||
assert_eq!(itr.len(), count-idx);
|
||||
assert!(itr.next().is_some());
|
||||
}
|
||||
assert_eq!(itr.size_hint(), (0, Some(0)));
|
||||
assert_eq!(itr.len(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
check_iter_size_hint(EnumSet::<$e>::new());
|
||||
check_iter_size_hint(EnumSet::<$e>::all());
|
||||
let mut set = EnumSet::new();
|
||||
set.insert($e::A);
|
||||
set.insert($e::C);
|
||||
set.insert($e::E);
|
||||
check_iter_size_hint(set);
|
||||
}
|
||||
|
||||
/// Check that advanced iterator operations like filter and collect work properly.
|
||||
#[test]
|
||||
fn iter_advanced_ops_test() {
|
||||
let set = $e::A | $e::B | $e::C | $e::E;
|
||||
let set2 = set.iter().filter(|&v| v != $e::B).collect::<EnumSet<_>>();
|
||||
assert_eq!(set2, $e::A | $e::C | $e::E);
|
||||
}
|
||||
|
||||
/// Basic test for arithmetic operators on bitsets.
|
||||
#[test]
|
||||
fn basic_ops_test() {
|
||||
assert_eq!(($e::A | $e::B) | ($e::B | $e::C), $e::A | $e::B | $e::C);
|
||||
assert_eq!(($e::A | $e::B) & ($e::B | $e::C), $e::B);
|
||||
assert_eq!(($e::A | $e::B) ^ ($e::B | $e::C), $e::A | $e::C);
|
||||
assert_eq!(($e::A | $e::B) - ($e::B | $e::C), $e::A);
|
||||
assert_eq!($e::A | !$e::A, EnumSet::<$e>::all());
|
||||
}
|
||||
|
||||
/// Basic test for mutate-in-place operators on bitsets.
|
||||
#[test]
|
||||
fn mutable_ops_test() {
|
||||
let mut set = $e::A | $e::B;
|
||||
assert_eq!(set, $e::A | $e::B);
|
||||
set |= $e::C | $e::D;
|
||||
assert_eq!(set, $e::A | $e::B | $e::C | $e::D);
|
||||
set -= $e::C;
|
||||
assert_eq!(set, $e::A | $e::B | $e::D);
|
||||
set ^= $e::B | $e::E;
|
||||
assert_eq!(set, $e::A | $e::D | $e::E);
|
||||
set &= $e::A | $e::E | $e::F;
|
||||
assert_eq!(set, $e::A | $e::E);
|
||||
}
|
||||
|
||||
/// Basic test for disjoint/subset checking.
|
||||
#[test]
|
||||
fn test_disjoint_subset() {
|
||||
assert!(($e::A | $e::B | $e::C).is_disjoint($e::D | $e::E | $e::F));
|
||||
assert!(!($e::A | $e::B | $e::C | $e::D).is_disjoint($e::D | $e::E | $e::F));
|
||||
assert!(($e::A | $e::B).is_subset($e::A | $e::B | $e::C));
|
||||
assert!(!($e::A | $e::D).is_subset($e::A | $e::B | $e::C));
|
||||
}
|
||||
|
||||
/// Basic test that converting to and from an integer works as expected.
|
||||
#[test]
|
||||
fn to_from_roundtrip() {
|
||||
let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G;
|
||||
if EnumSet::<$e>::bit_width() < 128 {
|
||||
assert_eq!(EnumSet::from_u128(value.as_u128()), value);
|
||||
}
|
||||
if EnumSet::<$e>::bit_width() < 64 {
|
||||
assert_eq!(EnumSet::from_u64(value.as_u64()), value);
|
||||
}
|
||||
if EnumSet::<$e>::bit_width() < 32 {
|
||||
assert_eq!(EnumSet::from_u32(value.as_u32()), value);
|
||||
}
|
||||
if EnumSet::<$e>::bit_width() < 16 {
|
||||
assert_eq!(EnumSet::from_u16(value.as_u16()), value);
|
||||
}
|
||||
if EnumSet::<$e>::bit_width() < 8 {
|
||||
assert_eq!(EnumSet::from_u8(value.as_u8()), value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests that EnumSet correctly detects conversions containing invalid bits
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn should_panic_on_invalid_bits() {
|
||||
if EnumSet::<$e>::variant_count() == 128 {
|
||||
panic!("(test skipped)")
|
||||
}
|
||||
EnumSet::<$e>::from_u128(!0);
|
||||
}
|
||||
|
||||
/// An advanced test to ensure that sets of enumsets work correctly.
|
||||
#[test]
|
||||
fn test_enumset_in_std_sets() {
|
||||
const SET_TEST_A: EnumSet<$e> = enum_set!($e::A | $e::B | $e::C);
|
||||
const SET_TEST_B: EnumSet<$e> = enum_set!($e::A | $e::B | $e::D);
|
||||
const SET_TEST_C: EnumSet<$e> = enum_set!($e::A | $e::B | $e::E);
|
||||
const SET_TEST_D: EnumSet<$e> = enum_set!($e::A | $e::B | $e::F);
|
||||
const SET_TEST_E: EnumSet<$e> = enum_set!($e::A | $e::B | $e::G);
|
||||
macro_rules! test_set {
|
||||
($set:ident) => {{
|
||||
assert!(!$set.contains(&SET_TEST_A));
|
||||
assert!(!$set.contains(&SET_TEST_B));
|
||||
assert!(!$set.contains(&SET_TEST_C));
|
||||
assert!(!$set.contains(&SET_TEST_D));
|
||||
assert!(!$set.contains(&SET_TEST_E));
|
||||
$set.insert(SET_TEST_A);
|
||||
$set.insert(SET_TEST_C);
|
||||
assert!($set.contains(&SET_TEST_A));
|
||||
assert!(!$set.contains(&SET_TEST_B));
|
||||
assert!($set.contains(&SET_TEST_C));
|
||||
assert!(!$set.contains(&SET_TEST_D));
|
||||
assert!(!$set.contains(&SET_TEST_E));
|
||||
$set.remove(&SET_TEST_C);
|
||||
$set.remove(&SET_TEST_D);
|
||||
assert!($set.contains(&SET_TEST_A));
|
||||
assert!(!$set.contains(&SET_TEST_B));
|
||||
assert!(!$set.contains(&SET_TEST_C));
|
||||
assert!(!$set.contains(&SET_TEST_D));
|
||||
assert!(!$set.contains(&SET_TEST_E));
|
||||
$set.insert(SET_TEST_A);
|
||||
$set.insert(SET_TEST_D);
|
||||
assert!($set.contains(&SET_TEST_A));
|
||||
assert!(!$set.contains(&SET_TEST_B));
|
||||
assert!(!$set.contains(&SET_TEST_C));
|
||||
assert!($set.contains(&SET_TEST_D));
|
||||
assert!(!$set.contains(&SET_TEST_E));
|
||||
}}
|
||||
}
|
||||
|
||||
let mut hash_set = HashSet::new();
|
||||
test_set!(hash_set);
|
||||
|
||||
let mut tree_set = BTreeSet::new();
|
||||
test_set!(tree_set);
|
||||
}
|
||||
|
||||
/// An advanced test that summing enumsets in iterators.
|
||||
#[test]
|
||||
fn sum_iterator_of_enumsets() {
|
||||
let target = $e::A | $e::B | $e::D | $e::E | $e::G | $e::H;
|
||||
|
||||
let list_a = [$e::A | $e::B, $e::D | $e::E, $e::G | $e::H];
|
||||
let sum_a: EnumSet<$e> = list_a.iter().map(|x| *x).sum();
|
||||
assert_eq!(target, sum_a);
|
||||
let sum_b: EnumSet<$e> = list_a.iter().sum();
|
||||
assert_eq!(target, sum_b);
|
||||
|
||||
let list_b = [$e::A, $e::B, $e::D, $e::E, $e::G, $e::H];
|
||||
let sum_c: EnumSet<$e> = list_b.iter().map(|x| *x).sum();
|
||||
assert_eq!(target, sum_c);
|
||||
let sum_d: EnumSet<$e> = list_b.iter().sum();
|
||||
assert_eq!(target, sum_d);
|
||||
}
|
||||
|
||||
/// Checks that the enumset has the expected size in memory.
|
||||
#[test]
|
||||
fn check_size() {
|
||||
assert_eq!(::std::mem::size_of::<EnumSet<$e>>(), $mem_size);
|
||||
}
|
||||
|
||||
/// Tests the conversion of const-length arrays to EnumSets.
|
||||
#[test]
|
||||
fn from_array() {
|
||||
assert!(EnumSet::<$e>::from([]).is_empty());
|
||||
assert_eq!(
|
||||
EnumSet::<$e>::from([$e::B, $e::E, $e::H]),
|
||||
enum_set!($e::B | $e::E | $e::H)
|
||||
);
|
||||
assert_eq!(
|
||||
EnumSet::<$e>::from([$e::A, $e::B, $e::C]),
|
||||
enum_set!($e::A | $e::B | $e::C)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! tests {
|
||||
($m:ident, $($tt:tt)*) => { mod $m { use super::*; $($tt)*; } }
|
||||
}
|
||||
|
||||
tests!(small_enum, test_enum!(SmallEnum, 4, ordered));
|
||||
tests!(small_enum_explicit_derive, test_enum!(SmallEnumExplicitDerive, 4, ordered));
|
||||
tests!(large_enum, test_enum!(LargeEnum, 16, ordered));
|
||||
tests!(enum8, test_enum!(Enum8, 1, ordered));
|
||||
tests!(enum128, test_enum!(Enum128, 16, ordered));
|
||||
tests!(sparse_enum, test_enum!(SparseEnum, 16, ordered));
|
||||
tests!(repr_enum_u32, test_enum!(ReprEnum, 4, ordered));
|
||||
tests!(repr_enum_u64, test_enum!(ReprEnum2, 4, ordered));
|
||||
tests!(repr_enum_isize, test_enum!(ReprEnum3, 4, ordered));
|
||||
tests!(repr_enum_c, test_enum!(ReprEnum4, 4, ordered));
|
||||
tests!(giant_enum, test_enum!(GiantEnum, 104, ordered));
|
||||
tests!(small_array_enum, test_enum!(SmallArrayEnum, 8, ordered));
|
||||
tests!(marginal_array_enum_s2, test_enum!(MarginalArrayEnumS2, 16, ordered));
|
||||
tests!(marginal_array_enum_s2h, test_enum!(MarginalArrayEnumS2H, 16, ordered));
|
||||
tests!(marginal_array_enum_s3, test_enum!(MarginalArrayEnumS3, 24, ordered));
|
||||
tests!(compact_enum_a, test_enum!(CompactEnumA, 1));
|
||||
tests!(compact_enum_b, test_enum!(CompactEnumB, 1));
|
||||
tests!(msb_enum, test_enum!(MsbEnum, 8));
|
||||
tests!(msb_sparse_enum, test_enum!(MsbSparseEnum, 8));
|
||||
tests!(mask_enum, test_enum!(MaskEnum, 1, ordered));
|
||||
tests!(mask_sparse_enum, test_enum!(MaskSparseEnum, 8));
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum ThresholdEnum {
|
||||
A = 1, B, C, D,
|
||||
U8 = 0, U16 = 8, U32 = 16, U64 = 32, U128 = 64,
|
||||
}
|
||||
macro_rules! bits_tests {
|
||||
(
|
||||
$mod_name:ident, $threshold_expr:expr, ($($too_big_expr:expr),*), $ty:ty,
|
||||
$to:ident $try_to:ident $to_truncated:ident
|
||||
$from:ident $try_from:ident $from_truncated:ident
|
||||
) => {
|
||||
mod $mod_name {
|
||||
use super::*;
|
||||
use crate::ThresholdEnum::*;
|
||||
|
||||
#[test]
|
||||
fn to_from_basic() {
|
||||
for &mask in &[
|
||||
$threshold_expr | B | C | D,
|
||||
$threshold_expr | A | D,
|
||||
$threshold_expr | B | C,
|
||||
] {
|
||||
assert_eq!(mask, EnumSet::<ThresholdEnum>::$from(mask.$to()));
|
||||
assert_eq!(mask.$to_truncated(), mask.$to());
|
||||
assert_eq!(Some(mask.$to()), mask.$try_to())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn from_invalid() {
|
||||
let invalid_mask: $ty = 0x80;
|
||||
EnumSet::<ThresholdEnum>::$from(invalid_mask);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_from_invalid() {
|
||||
assert!(EnumSet::<ThresholdEnum>::$try_from(0xFF).is_none());
|
||||
}
|
||||
|
||||
$(
|
||||
#[test]
|
||||
fn try_to_overflow() {
|
||||
let set: EnumSet<ThresholdEnum> = $too_big_expr.into();
|
||||
assert!(set.$try_to().is_none());
|
||||
}
|
||||
)*
|
||||
|
||||
#[test]
|
||||
fn truncated_overflow() {
|
||||
let trunc_invalid = EnumSet::<ThresholdEnum>::$from_truncated(0xFE);
|
||||
assert_eq!(A | B | C | D, trunc_invalid);
|
||||
$(
|
||||
let set: EnumSet<ThresholdEnum> = $too_big_expr | A;
|
||||
assert_eq!(2, set.$to_truncated());
|
||||
)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bits_tests!(test_u8_bits, U8, (U16), u8,
|
||||
as_u8 try_as_u8 as_u8_truncated from_u8 try_from_u8 from_u8_truncated);
|
||||
bits_tests!(test_u16_bits, U16, (U32), u16,
|
||||
as_u16 try_as_u16 as_u16_truncated from_u16 try_from_u16 from_u16_truncated);
|
||||
bits_tests!(test_u32_bits, U32, (U64), u32,
|
||||
as_u32 try_as_u32 as_u32_truncated from_u32 try_from_u32 from_u32_truncated);
|
||||
bits_tests!(test_u64_bits, U64, (U128), u64,
|
||||
as_u64 try_as_u64 as_u64_truncated from_u64 try_from_u64 from_u64_truncated);
|
||||
bits_tests!(test_u128_bits, U128, (), u128,
|
||||
as_u128 try_as_u128 as_u128_truncated from_u128 try_from_u128 from_u128_truncated);
|
||||
bits_tests!(test_usize_bits, U32, (U128), usize,
|
||||
as_usize try_as_usize as_usize_truncated
|
||||
from_usize try_from_usize from_usize_truncated);
|
||||
|
||||
impl Display for Enum8 {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
Debug::fmt(self, f)
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn test_display_impl() {
|
||||
assert_eq!((Enum8::A | Enum8::D | Enum8::H).to_string(), "A | D | H");
|
||||
}
|
||||
|
||||
mod tests_without_imports {
|
||||
// This deliberately does not use super::* or crate::*
|
||||
|
||||
// The constants below should compile despite not having EnumSet or enumset
|
||||
// in scope.
|
||||
|
||||
const EMPTY: crate::EnumSet<super::SmallEnum> = crate::enum_set!();
|
||||
const CONST_SET: crate::EnumSet<super::SmallEnum> = crate::enum_set!(super::SmallEnum::A | super::SmallEnum::C);
|
||||
const CONST_1_SET: crate::EnumSet<super::SmallEnum> = crate::enum_set!(super::SmallEnum::A);
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use enumset::*;
|
||||
|
||||
macro_rules! read_slice {
|
||||
($set:expr, $size:expr) => {{
|
||||
let mut arr = [0; $size];
|
||||
$set.copy_into_slice(&mut arr);
|
||||
arr
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! try_read_slice {
|
||||
($set:expr, $size:expr) => {{
|
||||
let mut arr = [0; $size];
|
||||
match $set.try_copy_into_slice(&mut arr) {
|
||||
Some(()) => Some(arr),
|
||||
None => None,
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! read_slice_truncated {
|
||||
($set:expr, $size:expr) => {{
|
||||
let mut arr = [0; $size];
|
||||
$set.copy_into_slice_truncated(&mut arr);
|
||||
arr
|
||||
}};
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum8 {
|
||||
A, B, C, D, E, F, G,
|
||||
// H omitted for non-existent bit test
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum16 {
|
||||
A, B, C, D, E=8, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum32 {
|
||||
A, B, C, D, E=16, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum64 {
|
||||
A, B, C, D, E=32, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum128 {
|
||||
A, B, C, D, E=64, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum192 {
|
||||
A, B, C, D, E=128, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum Enum256 {
|
||||
A, B, C, D, E=192, F, G, H,
|
||||
}
|
||||
|
||||
macro_rules! check_simple_conversion {
|
||||
($mod:ident, $e:ident) => {
|
||||
mod $mod {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn to_integer() {
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_u8());
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_u16());
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_u32());
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_u64());
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_u128());
|
||||
assert_eq!(7,
|
||||
($e::A | $e::B | $e::C).as_usize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_from_integer() {
|
||||
assert_eq!(Some($e::A | $e::B | $e::C),
|
||||
EnumSet::try_from_u8(7));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_u8(7 | (1 << 7)));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_u16(7 | (1 << 15)));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_u32(7 | (1 << 31)));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_usize(7 | (1 << 31)));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_u64(7 | (1 << 63)));
|
||||
assert_eq!(None,
|
||||
EnumSet::<$e>::try_from_u128(7 | (1 << 127)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_integer_truncated() {
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u8_truncated(7));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u8_truncated(7 | (1 << 7)));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u16_truncated(7 | (1 << 15)));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u32_truncated(7 | (1 << 31)));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_usize_truncated(7 | (1 << 31)));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u64_truncated(7 | (1 << 63)));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::from_u128_truncated(7 | (1 << 127)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_to_array() {
|
||||
// array tests
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array_truncated(),
|
||||
[]);
|
||||
assert_eq!(EnumSet::<$e>::empty().as_array_truncated(),
|
||||
[]);
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array(),
|
||||
[7]);
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array(),
|
||||
[7, 0]);
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array(),
|
||||
[7, 0, 0]);
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array(),
|
||||
[7, 0, 0, 0]);
|
||||
assert_eq!(($e::A | $e::B | $e::C).as_array(),
|
||||
[7, 0, 0, 0, 0]);
|
||||
|
||||
// slice tests
|
||||
assert_eq!(read_slice!($e::A | $e::B | $e::C, 1),
|
||||
[7]);
|
||||
assert_eq!(read_slice!($e::A | $e::B | $e::C, 2),
|
||||
[7, 0]);
|
||||
assert_eq!(read_slice!($e::A | $e::B | $e::C, 3),
|
||||
[7, 0, 0]);
|
||||
assert_eq!(read_slice!($e::A | $e::B | $e::C, 4),
|
||||
[7, 0, 0, 0]);
|
||||
assert_eq!(read_slice!($e::A | $e::B | $e::C, 5),
|
||||
[7, 0, 0, 0, 0]);
|
||||
|
||||
// slice tests truncated
|
||||
assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 1),
|
||||
[7]);
|
||||
assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 2),
|
||||
[7, 0]);
|
||||
assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 3),
|
||||
[7, 0, 0]);
|
||||
assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 4),
|
||||
[7, 0, 0, 0]);
|
||||
assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 5),
|
||||
[7, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_from_array() {
|
||||
// array tests
|
||||
assert_eq!(EnumSet::<$e>::empty(),
|
||||
EnumSet::<$e>::from_array([]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array([7]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array([7, 0, 0]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array([7, 0, 0, 0]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array([7, 0, 0, 0, 0]));
|
||||
|
||||
// array tests
|
||||
assert_eq!(EnumSet::<$e>::empty(),
|
||||
EnumSet::<$e>::from_slice(&[]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice(&[7]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice(&[7, 0, 0]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice(&[7, 0, 0, 0]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice(&[7, 0, 0, 0, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_from_array_truncated() {
|
||||
// array tests
|
||||
assert_eq!(EnumSet::<$e>::empty(),
|
||||
EnumSet::<$e>::from_array_truncated([]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array_truncated([7 | (1 << 31)]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array_truncated([7, 0, 16]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array_truncated([7, 0, 0, 16]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_array_truncated([7, 0, 0, 0, 16]));
|
||||
|
||||
// array tests
|
||||
assert_eq!(EnumSet::<$e>::empty(),
|
||||
EnumSet::<$e>::from_slice_truncated(&[]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice_truncated(&[7 | (1 << 31)]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice_truncated(&[7, 0, 16]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice_truncated(&[7, 0, 0, 16]));
|
||||
assert_eq!($e::A | $e::B | $e::C,
|
||||
EnumSet::<$e>::from_slice_truncated(&[7, 0, 0, 0, 16]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_u8() {
|
||||
EnumSet::<$e>::from_u8(7 | (1 << 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_u16() {
|
||||
EnumSet::<$e>::from_u16(7 | (1 << 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_u32() {
|
||||
EnumSet::<$e>::from_u32(7 | (1 << 31));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_usize() {
|
||||
EnumSet::<$e>::from_usize(7 | (1 << 31));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_u64() {
|
||||
EnumSet::<$e>::from_u64(7 | (1 << 63));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_u128() {
|
||||
EnumSet::<$e>::from_u128(7 | (1 << 127));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_to_array() {
|
||||
($e::A | $e::B | $e::C).as_array::<0>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_to_slice() {
|
||||
read_slice!($e::A | $e::B | $e::C, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_array_1() {
|
||||
EnumSet::<$e>::from_array([7 | (1 << 63), 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_slice_1() {
|
||||
EnumSet::<$e>::from_slice(&[7 | (1 << 63), 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_array_2() {
|
||||
EnumSet::<$e>::from_array([7, 0, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_from_slice_2() {
|
||||
EnumSet::<$e>::from_slice(&[7, 0, 0, 0, 1]);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
check_simple_conversion!(enum_8_simple, Enum8);
|
||||
check_simple_conversion!(enum_16_simple, Enum16);
|
||||
check_simple_conversion!(enum_32_simple, Enum32);
|
||||
check_simple_conversion!(enum_64_simple, Enum64);
|
||||
check_simple_conversion!(enum_128_simple, Enum128);
|
||||
check_simple_conversion!(enum_192_simple, Enum192);
|
||||
check_simple_conversion!(enum_256_simple, Enum256);
|
||||
|
||||
macro_rules! check_oversized_64 {
|
||||
($mod:ident, $e:ident) => {
|
||||
mod $mod {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn downcast_to_u64() {
|
||||
assert_eq!(Some(7), ($e::A | $e::B | $e::C).try_as_u64());
|
||||
assert_eq!(Some([7]), ($e::A | $e::B | $e::C).try_as_array());
|
||||
assert_eq!(Some([7]), try_read_slice!($e::A | $e::B | $e::C, 1));
|
||||
|
||||
assert_eq!(None, ($e::E | $e::F | $e::G).try_as_u64());
|
||||
assert_eq!(None, ($e::E | $e::F | $e::G).try_as_array::<1>());
|
||||
assert_eq!(None, try_read_slice!($e::E | $e::F | $e::G, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downcast_to_u64_truncated() {
|
||||
assert_eq!(0, ($e::E | $e::F | $e::G).as_u64_truncated());
|
||||
assert_eq!([0], ($e::E | $e::F | $e::G).as_array_truncated());
|
||||
assert_eq!([0], read_slice_truncated!($e::E | $e::F | $e::G, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_to_u64() {
|
||||
($e::E | $e::F | $e::G).as_u64();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
check_oversized_64!(enum_128_oversized_64, Enum128);
|
||||
check_oversized_64!(enum_192_oversized_64, Enum192);
|
||||
check_oversized_64!(enum_256_oversized_64, Enum256);
|
||||
|
||||
macro_rules! check_oversized_128 {
|
||||
($mod:ident, $e:ident) => {
|
||||
mod $mod {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn downcast_to_u128() {
|
||||
assert_eq!(7, ($e::A | $e::B | $e::C).as_u128());
|
||||
assert_eq!(Some(7), ($e::A | $e::B | $e::C).try_as_u128());
|
||||
assert_eq!(None, ($e::E | $e::F | $e::G).try_as_u128());
|
||||
assert_eq!(0, ($e::E | $e::F | $e::G).as_u128_truncated());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn fail_to_u128() {
|
||||
($e::E | $e::F | $e::G).as_u128();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
check_oversized_128!(enum_192_oversized_128, Enum192);
|
||||
check_oversized_128!(enum_256_oversized_128, Enum256);
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use enumset::*;
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "u16")]
|
||||
enum ReprEnum {
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
}
|
||||
|
||||
const _: () = assert!(EnumSet::<ReprEnum>::all().as_repr() == 0b11111111);
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
let mut set = EnumSet::<ReprEnum>::new();
|
||||
set.insert(ReprEnum::B);
|
||||
set.insert(ReprEnum::F);
|
||||
|
||||
let repr: u16 = set.as_repr();
|
||||
assert_eq!((1 << 1) | (1 << 5), repr,);
|
||||
|
||||
let set2 = unsafe { EnumSet::<ReprEnum>::from_repr_unchecked(repr) };
|
||||
assert_eq!(set, set2);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
#![cfg(feature = "serde")]
|
||||
#![deny(warnings)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use enumset::*;
|
||||
use serde_derive::*;
|
||||
|
||||
// Test resistance against shadowed types.
|
||||
type Some = ();
|
||||
type None = ();
|
||||
type Result = ();
|
||||
|
||||
#[derive(Serialize, Deserialize, EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "list")]
|
||||
pub enum ListEnum {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "map")]
|
||||
pub enum MapEnum {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "array")]
|
||||
pub enum ArrayEnum {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
pub enum LargeEnum {
|
||||
A, B, C, D, E=200, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "u128")]
|
||||
pub enum ReprEnum {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "u128", serialize_deny_unknown)]
|
||||
pub enum DenyUnknownEnum {
|
||||
A, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(repr = "u64", serialize_repr = "u32")]
|
||||
#[rustfmt::skip]
|
||||
pub enum MixedEnum {
|
||||
A = 10, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
#[derive(EnumSetType, Debug)]
|
||||
#[enumset(serialize_repr = "array", serialize_deny_unknown)]
|
||||
#[rustfmt::skip]
|
||||
pub enum DenyUnknownEnumArray {
|
||||
A = 40, B, C, D, E, F, G, H,
|
||||
}
|
||||
|
||||
macro_rules! serde_test_simple {
|
||||
($e:ident, $ser_size:expr) => {
|
||||
const VALUES: &[EnumSet<$e>] = &[
|
||||
enum_set!(),
|
||||
enum_set!($e::A | $e::C | $e::D | $e::F | $e::E | $e::G),
|
||||
enum_set!($e::A),
|
||||
enum_set!($e::H),
|
||||
enum_set!($e::A | $e::B),
|
||||
enum_set!($e::A | $e::B | $e::C | $e::D),
|
||||
enum_set!($e::A | $e::B | $e::C | $e::D | $e::F | $e::G | $e::H),
|
||||
enum_set!($e::G | $e::H),
|
||||
enum_set!($e::E | $e::F | $e::G | $e::H),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn serialize_deserialize_test_bincode() {
|
||||
for &value in VALUES {
|
||||
let serialized = bincode::serialize(&value).unwrap();
|
||||
let deserialized = bincode::deserialize::<EnumSet<$e>>(&serialized).unwrap();
|
||||
assert_eq!(value, deserialized);
|
||||
if $ser_size != !0 {
|
||||
assert_eq!(serialized.len(), $ser_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialize_deserialize_test_json() {
|
||||
for &value in VALUES {
|
||||
let serialized = serde_json::to_string(&value).unwrap();
|
||||
let deserialized = serde_json::from_str::<EnumSet<$e>>(&serialized).unwrap();
|
||||
assert_eq!(value, deserialized);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! serde_test {
|
||||
($e:ident, $ser_size:expr) => {
|
||||
serde_test_simple!($e, $ser_size);
|
||||
|
||||
#[test]
|
||||
fn deserialize_all_test() {
|
||||
let serialized = bincode::serialize(&!0u128).unwrap();
|
||||
let deserialized = bincode::deserialize::<EnumSet<$e>>(&serialized).unwrap();
|
||||
assert_eq!(EnumSet::<$e>::all(), deserialized);
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! tests {
|
||||
($m:ident, $($tt:tt)*) => { mod $m { use super::*; $($tt)*; } }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deny_unknown() {
|
||||
let serialized = bincode::serialize(&!0u128).unwrap();
|
||||
let deserialized = bincode::deserialize::<EnumSet<DenyUnknownEnum>>(&serialized);
|
||||
assert!(deserialized.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deny_unknown_array() {
|
||||
let serialized = bincode::serialize(&!0u128).unwrap();
|
||||
let deserialized = bincode::deserialize::<EnumSet<DenyUnknownEnumArray>>(&serialized);
|
||||
assert!(deserialized.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json_reprs_basic() {
|
||||
assert_eq!(
|
||||
ListEnum::A | ListEnum::C | ListEnum::F,
|
||||
serde_json::from_str::<EnumSet<ListEnum>>(r#"["A","C","F"]"#).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
MapEnum::A | MapEnum::C | MapEnum::F,
|
||||
serde_json::from_str::<EnumSet<MapEnum>>(r#"{"A":true,"C":true,"F":true}"#).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
ReprEnum::A | ReprEnum::C | ReprEnum::D,
|
||||
serde_json::from_str::<EnumSet<ReprEnum>>("13").unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
r#"["A","C","F"]"#,
|
||||
serde_json::to_string(&(ListEnum::A | ListEnum::C | ListEnum::F)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
r#"{"A":true,"C":true,"F":true}"#,
|
||||
serde_json::to_string(&(MapEnum::A | MapEnum::C | MapEnum::F)).unwrap()
|
||||
);
|
||||
assert_eq!("13", serde_json::to_string(&(ReprEnum::A | ReprEnum::C | ReprEnum::D)).unwrap());
|
||||
assert_eq!(
|
||||
"[13]",
|
||||
serde_json::to_string(&(ArrayEnum::A | ArrayEnum::C | ArrayEnum::D)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json_reprs_edge_cases() {
|
||||
assert_eq!(MapEnum::A | MapEnum::C | MapEnum::F,
|
||||
serde_json::from_str::<EnumSet<MapEnum>>(r#"{"D":false,"A":true,"E":false,"C":true,"F":true}"#).unwrap());
|
||||
assert_eq!(LargeEnum::A | LargeEnum::B | LargeEnum::C | LargeEnum::D,
|
||||
serde_json::from_str::<EnumSet<LargeEnum>>(r#"[15]"#).unwrap());
|
||||
}
|
||||
|
||||
tests!(list_enum, serde_test_simple!(ListEnum, !0));
|
||||
tests!(map_enum, serde_test_simple!(MapEnum, !0));
|
||||
tests!(array_enum, serde_test_simple!(ArrayEnum, !0));
|
||||
tests!(large_enum, serde_test_simple!(LargeEnum, !0));
|
||||
tests!(repr_enum, serde_test!(ReprEnum, 16));
|
||||
tests!(deny_unknown_enum, serde_test_simple!(DenyUnknownEnum, 16));
|
||||
tests!(mixed_enum, serde_test_simple!(MixedEnum, 4));
|
||||
tests!(deny_unknown_enum_array, serde_test_simple!(DenyUnknownEnumArray, 16));
|
||||
Reference in new issue
Block a user