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:
swaitsandClaude Opus 4.6 committed 2026-03-29 20:42:54 -06:00
1 parent 7064110293
commit 3102fc747a
17624 files changed
+4564928 -38

No files matched your search

+1
View File
@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"311f9b97b62dc8f7fa02efa5349f8227cbdb9720571239bee8ff427ca3f20618","Cargo.lock":"2f48e93ef41dba9f47c7b658bc9467eba42470abb70fa1a966db4bd9ce085b5d","Cargo.toml":"b5d1f53d814d7e9ab8bdfc176ea93a1cebf2159494b14d69861db8347e380c92","Cargo.toml.orig":"a41207cbc3faf8c7fc9f9736b529edb9f03f28f0c5f9d27115ddf72e3cf76ff5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c87c7f72fd595c10bbe55b688ecb609e2e5b7f610410d558efce1ba8dc16f7b3","README.md":"d45f82ad73b39aad91f85d0688bc6a94402293c40c295d0cab7b2a9b7225677b","src/const_eval.rs":"b07657ef27ec6a8e36fe07fffcb4dd0848767a40fcac7abfc3bcef15b1b4d6ec","src/gen.rs":"63fe1d282afb9893f3308e97709a56d59b8b6c7150fdce1062ab58459a83e4fd","src/lib.rs":"8f884fdd39a741f6d355db8fabea02a507fd7aa6a112b54b5b94e70653d65221","src/plan.rs":"32b7b36514d03069a427fe159babdb34ce7b621407d80912df2d53296240c00f"},"package":"f43e744e4ea338060faee68ed933e46e722fb7f3617e722a5772d7e856d8b3ce"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "a808e1de1f744c98cc33967da31513a78665ba2d"
},
"path_in_vcs": "enumset_derive"
}
+158
View File
@@ -0,0 +1,158 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[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 = "enumset_derive"
version = "0.14.0"
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 = "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-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 = "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 = "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",
]
+53
View File
@@ -0,0 +1,53 @@
# 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"
name = "enumset_derive"
version = "0.14.0"
authors = ["Alissa Rao <aura@aura.moe>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "An internal helper crate for enumset. Not public API."
documentation = "https://docs.rs/enumset_derive/latest/enumset_derive/"
readme = "README.md"
license = "MIT/Apache-2.0"
repository = "https://github.com/Lymia/enumset"
[features]
serde2_deprecation_warning = []
std_deprecation_warning = []
[lib]
name = "enumset_derive"
path = "src/lib.rs"
proc-macro = true
[dependencies.darling]
version = "0.21"
default-features = false
[dependencies.proc-macro-crate]
version = "3"
optional = true
[dependencies.proc-macro2]
version = "1"
[dependencies.quote]
version = "1"
[dependencies.syn]
version = "2"
+201
View File
@@ -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.
+26
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
An internal helper crate for [enumset](https://github.com/Lymia/enumset). Not public API.
+44
View File
@@ -0,0 +1,44 @@
use crate::error;
use syn::spanned::Spanned;
use syn::{BinOp, Expr, ExprBinary, Lit, UnOp};
pub fn eval_literal(expr: &Expr) -> syn::Result<i64> {
match expr {
Expr::Binary(binary) => match binary.op {
BinOp::Add(_) => eval_bin(binary, |a, b| a.checked_add(b)),
BinOp::Sub(_) => eval_bin(binary, |a, b| a.checked_sub(b)),
BinOp::Mul(_) => eval_bin(binary, |a, b| a.checked_mul(b)),
BinOp::Div(_) => eval_bin(binary, |a, b| a.checked_div(b)),
BinOp::Rem(_) => eval_bin(binary, |a, b| a.checked_rem(b)),
BinOp::BitXor(_) => eval_bin(binary, |a, b| Some(a ^ b)),
BinOp::BitAnd(_) => eval_bin(binary, |a, b| Some(a & b)),
BinOp::BitOr(_) => eval_bin(binary, |a, b| Some(a | b)),
BinOp::Shl(_) => eval_bin(binary, |a, b| a.checked_shl(b.try_into().ok()?)),
BinOp::Shr(_) => eval_bin(binary, |a, b| a.checked_shr(b.try_into().ok()?)),
_ => error(expr.span(), "Expression not supported by enumset.")?,
},
Expr::Group(group) => eval_literal(&group.expr),
Expr::Lit(lit) => match &lit.lit {
Lit::Int(lit_int) => match lit_int.base10_parse::<i64>() {
Ok(val) => Ok(val),
Err(_) => error(expr.span(), "Enum discriminants must fit into `isize`.")?,
},
_ => error(expr.span(), "Expression not supported by enumset.")?,
},
Expr::Paren(paren) => eval_literal(&paren.expr),
Expr::Unary(unary) => match unary.op {
UnOp::Not(_) => Ok(!eval_literal(&unary.expr)?),
UnOp::Neg(_) => Ok(-eval_literal(&unary.expr)?),
_ => error(expr.span(), "Expression not supported by enumset.")?,
},
_ => error(expr.span(), "Expression not supported by enumset.")?,
}
}
fn eval_bin(binary: &ExprBinary, op: impl FnOnce(i64, i64) -> Option<i64>) -> syn::Result<i64> {
let result = op(eval_literal(&binary.left)?, eval_literal(&binary.right)?);
match result {
None => error(binary.span(), "Error while evaluating discriminator."),
Some(x) => Ok(x),
}
}
+803
View File
@@ -0,0 +1,803 @@
//! This module handles generating the actual code to allow an enum type to be used as a bitset.
use crate::plan::{EnumSetInfo, InternalRepr, SerdeRepr};
use proc_macro2::{Literal, Span, TokenStream as SynTokenStream};
use quote::*;
use syn::{Lit, LitInt};
struct Paths {
enumset: SynTokenStream,
typed_enumset: SynTokenStream,
core: SynTokenStream,
internal: SynTokenStream,
serde: SynTokenStream,
}
impl Paths {
fn from(info: &EnumSetInfo) -> Paths {
let name = &info.name;
let enumset = match &info.crate_name {
Some(crate_name) => quote!(::#crate_name),
None => {
#[cfg(feature = "proc-macro-crate")]
{
use proc_macro_crate::FoundCrate;
let crate_name = proc_macro_crate::crate_name("enumset");
match crate_name {
Ok(FoundCrate::Name(name)) => {
let ident =
proc_macro2::Ident::new(&name, proc_macro2::Span::call_site());
quote!(::#ident)
}
_ => quote!(::enumset),
}
}
#[cfg(not(feature = "proc-macro-crate"))]
{
quote!(::enumset)
}
}
};
let typed_enumset = quote!(#enumset::EnumSet<#name>);
let core = quote!(#enumset::__internal::core_export);
let internal = quote!(#enumset::__internal);
let serde = quote!(#enumset::__internal::serde);
Paths { enumset, typed_enumset, core, internal, serde }
}
}
/// Generates the actual `EnumSetType` impl.
pub fn generate_code(info: EnumSetInfo) -> SynTokenStream {
let paths = Paths::from(&info);
let name = &info.name;
let enumset = &paths.enumset;
let typed_enumset = &paths.typed_enumset;
let core = &paths.core;
let internal = &paths.internal;
let serde = &paths.serde;
let is_uninhabited = info.variants.is_empty();
let repr = match info.internal_repr() {
InternalRepr::U8 => quote! { u8 },
InternalRepr::U16 => quote! { u16 },
InternalRepr::U32 => quote! { u32 },
InternalRepr::U64 => quote! { u64 },
InternalRepr::U128 => quote! { u128 },
InternalRepr::Array(size) => quote! { #internal::ArrayRepr<{ #size }> },
};
let variant_map = info.variant_map();
let all_variants = match info.internal_repr() {
InternalRepr::U8 | InternalRepr::U16 | InternalRepr::U32 | InternalRepr::U64 => {
let lit = Literal::u64_unsuffixed(variant_map[0]);
quote! { #lit }
}
InternalRepr::U128 => {
let lit = Literal::u128_unsuffixed(
variant_map[0] as u128 | variant_map.get(1).map_or(0, |x| (*x as u128) << 64),
);
quote! { #lit }
}
InternalRepr::Array(size) => {
let mut new = Vec::new();
for i in 0..size {
new.push(Literal::u64_unsuffixed(*variant_map.get(i).unwrap_or(&0)));
}
quote! { #internal::ArrayRepr::<{ #size }>([#(#new,)*]) }
}
};
//
// Implements operator overloading on the enum type.
//
let impl_ops = if info.no_ops {
quote! {}
} else {
quote! {
#[automatically_derived]
impl<O: Into<#typed_enumset>> #core::ops::Sub<O> for #name {
type Output = #typed_enumset;
fn sub(self, other: O) -> Self::Output {
#enumset::EnumSet::only(self) - other.into()
}
}
#[automatically_derived]
impl<O: Into<#typed_enumset>> #core::ops::BitAnd<O> for #name {
type Output = #typed_enumset;
fn bitand(self, other: O) -> Self::Output {
#enumset::EnumSet::only(self) & other.into()
}
}
#[automatically_derived]
impl<O: Into<#typed_enumset>> #core::ops::BitOr<O> for #name {
type Output = #typed_enumset;
fn bitor(self, other: O) -> Self::Output {
#enumset::EnumSet::only(self) | other.into()
}
}
#[automatically_derived]
impl<O: Into<#typed_enumset>> #core::ops::BitXor<O> for #name {
type Output = #typed_enumset;
fn bitxor(self, other: O) -> Self::Output {
#enumset::EnumSet::only(self) ^ other.into()
}
}
#[automatically_derived]
impl #core::ops::Not for #name {
type Output = #typed_enumset;
fn not(self) -> Self::Output {
!#enumset::EnumSet::only(self)
}
}
#[automatically_derived]
impl #core::cmp::PartialEq<#typed_enumset> for #name {
fn eq(&self, other: &#typed_enumset) -> bool {
#enumset::EnumSet::only(*self) == *other
}
}
}
};
//
// Implements serde support.
//
let serde_repr = info.serde_repr();
let impl_serde_ops = match serde_repr {
SerdeRepr::U8 | SerdeRepr::U16 | SerdeRepr::U32 | SerdeRepr::U64 | SerdeRepr::U128 => {
let (serialize_repr, from_fn, to_fn) = match serde_repr {
SerdeRepr::U8 => (quote! { u8 }, quote! { from_u8 }, quote! { to_u8 }),
SerdeRepr::U16 => (quote! { u16 }, quote! { from_u16 }, quote! { to_u16 }),
SerdeRepr::U32 => (quote! { u32 }, quote! { from_u32 }, quote! { to_u32 }),
SerdeRepr::U64 => (quote! { u64 }, quote! { from_u64 }, quote! { to_u64 }),
SerdeRepr::U128 => (quote! { u128 }, quote! { from_u128 }, quote! { to_u128 }),
_ => unreachable!(),
};
let check_unknown = if info.serialize_deny_unknown {
quote! {
let all_variants_cast =
<#repr as #enumset::__internal::EnumSetTypeRepr>::#to_fn(&#all_variants);
if value & !all_variants_cast != 0 {
use #serde::de::Error;
return #core::prelude::v1::Err(
D::Error::custom("enumset contains unknown bits")
)
}
}
} else {
quote! {}
};
quote! {
fn serialize<S: #serde::Serializer>(
set: #enumset::EnumSet<#name>, ser: S,
) -> #core::result::Result<S::Ok, S::Error> {
let value = <#repr as #enumset::__internal::EnumSetTypeRepr>::#to_fn(
&#internal::set::get(set),
);
#serde::Serialize::serialize(&value, ser)
}
fn deserialize<'de, D: #serde::Deserializer<'de>>(
de: D,
) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
let value = <#serialize_repr as #serde::Deserialize>::deserialize(de)?;
#check_unknown
let value = <#repr as #enumset::__internal::EnumSetTypeRepr>::#from_fn(value);
#core::prelude::v1::Ok(#internal::set::new(value & #all_variants))
}
}
}
SerdeRepr::List => {
let expecting_str = format!("a list of {name}");
quote! {
fn serialize<S: #serde::Serializer>(
set: #enumset::EnumSet<#name>, ser: S,
) -> #core::result::Result<S::Ok, S::Error> {
use #serde::ser::SerializeSeq;
let mut seq = ser.serialize_seq(#core::prelude::v1::Some(set.len()))?;
for bit in set {
seq.serialize_element(&bit)?;
}
seq.end()
}
fn deserialize<'de, D: #serde::Deserializer<'de>>(
de: D,
) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
struct Visitor;
impl <'de> #serde::de::Visitor<'de> for Visitor {
type Value = #enumset::EnumSet<#name>;
fn expecting(
&self, formatter: &mut #core::fmt::Formatter,
) -> #core::fmt::Result {
write!(formatter, #expecting_str)
}
fn visit_seq<A>(
mut self, mut seq: A,
) -> #core::result::Result<Self::Value, A::Error> where
A: #serde::de::SeqAccess<'de>
{
let mut accum = #enumset::EnumSet::<#name>::new();
while let #core::prelude::v1::Some(val) = seq.next_element::<#name>()? {
accum |= val;
}
#core::prelude::v1::Ok(accum)
}
}
de.deserialize_seq(Visitor)
}
}
}
SerdeRepr::Map => {
let expecting_str = format!("a map from {name} to bool");
quote! {
fn serialize<S: #serde::Serializer>(
set: #enumset::EnumSet<#name>, ser: S,
) -> #core::result::Result<S::Ok, S::Error> {
use #serde::ser::SerializeMap;
let mut map = ser.serialize_map(#core::prelude::v1::Some(set.len()))?;
for bit in set {
map.serialize_entry(&bit, &true)?;
}
map.end()
}
fn deserialize<'de, D: #serde::Deserializer<'de>>(
de: D,
) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
struct Visitor;
impl <'de> #serde::de::Visitor<'de> for Visitor {
type Value = #enumset::EnumSet<#name>;
fn expecting(
&self, formatter: &mut #core::fmt::Formatter,
) -> #core::fmt::Result {
write!(formatter, #expecting_str)
}
fn visit_map<A>(
mut self, mut map: A,
) -> #core::result::Result<Self::Value, A::Error> where
A: #serde::de::MapAccess<'de>
{
let mut accum = #enumset::EnumSet::<#name>::new();
while let #core::prelude::v1::Some((val, is_present)) =
map.next_entry::<#name, bool>()?
{
if is_present {
accum |= val;
}
}
#core::prelude::v1::Ok(accum)
}
}
de.deserialize_map(Visitor)
}
}
}
SerdeRepr::Array => {
let preferred_size = quote! {
<<#name as #internal::EnumSetTypePrivate>::Repr as #internal::EnumSetTypeRepr>
::PREFERRED_ARRAY_LEN
};
let (check_extra, convert_array) = if info.serialize_deny_unknown {
(
quote! {
if _val != 0 {
use #serde::de::Error;
return #core::prelude::v1::Err(
A::Error::custom("enumset contains unknown bits")
)
}
},
quote! {
use #serde::de::Error;
match #enumset::EnumSet::<#name>::try_from_array(accum) {
Some(x) => #core::prelude::v1::Ok(x),
None => #core::prelude::v1::Err(
A::Error::custom("enumset contains unknown bits")
),
}
},
)
} else {
(quote! {}, quote! {
#core::prelude::v1::Ok(#enumset::EnumSet::<#name>::from_array(accum))
})
};
quote! {
fn serialize<S: #serde::Serializer>(
set: #enumset::EnumSet<#name>, ser: S,
) -> #core::result::Result<S::Ok, S::Error> {
// read the enum as an array
let array = set.as_array::<{ #preferred_size }>();
// find the last non-zero value in the array
let mut end = array.len();
for i in (0..array.len()).rev() {
if array[i] != 0 {
break;
}
end = i + 1;
}
// serialize the array
#serde::Serialize::serialize(&array[..end], ser)
}
fn deserialize<'de, D: #serde::Deserializer<'de>>(
de: D,
) -> #core::result::Result<#enumset::EnumSet<#name>, D::Error> {
struct Visitor;
impl <'de> #serde::de::Visitor<'de> for Visitor {
type Value = #enumset::EnumSet<#name>;
fn expecting(
&self, formatter: &mut #core::fmt::Formatter,
) -> #core::fmt::Result {
write!(formatter, "a list of u64")
}
fn visit_seq<A>(
mut self, mut seq: A,
) -> #core::result::Result<Self::Value, A::Error> where
A: #serde::de::SeqAccess<'de>
{
let mut accum = [0; #preferred_size];
let mut i = 0;
while let #core::prelude::v1::Some(val) = seq.next_element::<u64>()? {
accum[i] = val;
i += 1;
if i == accum.len() {
break;
}
}
while let #core::prelude::v1::Some(_val) = seq.next_element::<u64>()? {
#check_extra
}
#convert_array
}
}
de.deserialize_seq(Visitor)
}
}
}
};
//
// Implement the core conversion function that maps enum variants to bits.
//
let impl_internal_conversions = create_enum_conversions(&info, &paths);
//
// Generate the code for `Eq` and other similar basic traits.
//
let impl_basic_traits = if info.no_super_impls {
quote! {}
} else {
let eq_impl = if is_uninhabited {
quote!(#core::unreachable!(concat!(stringify!(#name), " is uninhabited.")))
} else {
quote!((*self as u32) == (*other as u32))
};
quote! {
#[automatically_derived]
impl #core::cmp::PartialEq for #name {
fn eq(&self, other: &Self) -> bool {
#eq_impl
}
}
#[automatically_derived]
impl #core::cmp::Eq for #name { }
#[automatically_derived]
#[allow(clippy::expl_impl_clone_on_copy)]
impl #core::clone::Clone for #name {
fn clone(&self) -> Self {
*self
}
}
#[automatically_derived]
impl #core::marker::Copy for #name { }
}
};
//
// Generate the code for the explicit repr trait.
//
let impl_with_repr = if info.has_explicit_repr() {
quote! {
#[automatically_derived]
unsafe impl #enumset::EnumSetTypeWithRepr for #name {
type Repr = #repr;
}
}
} else {
quote! {}
};
//
// Generate the code for compile-time operations.
//
let impl_const_opers = create_enum_const_opers(&info, &paths, &repr);
//
// Generate the actual enumset trait.
//
let mut generated_warnings = SynTokenStream::new();
for (span, warning) in &info.warnings {
generated_warnings.extend(quote_spanned! {
*span => {
#[deprecated(note = #warning)]
#[allow(non_upper_case_globals)]
const _w: () = ();
let _ = _w;
}
});
}
let bit_width = info.bit_width();
let variant_count = info.variants.len() as u32;
let enum_repr = info.enum_repr();
let enum_discrim: Vec<_> = info.variants.iter().map(|x| x.discriminant).collect();
let enum_names: Vec<_> = info.variants.iter().map(|x| &x.name).collect();
quote! {
const _: () = {
// Double check fundamental assumptions baked into a lot of the code here.
#core::assert!(#core::mem::size_of::<#name>() <= #core::mem::size_of::<#enum_repr>());
#(#core::assert!(#enum_discrim == (#name::#enum_names as i64));)*
#[automatically_derived]
unsafe impl #internal::EnumSetTypePrivate for #name {
type Repr = #repr;
const ALL_BITS: Self::Repr = #all_variants;
const BIT_WIDTH: u32 = #bit_width;
const VARIANT_COUNT: u32 = #variant_count;
#impl_internal_conversions
#internal::__if_serde! {
#impl_serde_ops
}
}
#[automatically_derived]
unsafe impl #enumset::EnumSetType for #name { }
#impl_ops
#impl_with_repr
#impl_basic_traits
#impl_const_opers
fn __enumset_derive__generated_warnings() {
#generated_warnings
}
};
}
}
fn create_enum_conversions(info: &EnumSetInfo, paths: &Paths) -> SynTokenStream {
let name = &info.name;
let core = &paths.core;
let enum_repr = info.enum_repr();
let hint_is_transmute = quote! {
#[cfg(target_endian = "little")]
let r = *(&r as *const #enum_repr as *const #name);
#[cfg(target_endian = "big")]
let r = {
let offset =
#core::mem::size_of::<#enum_repr>() - #core::mem::size_of::<#name>();
let r = r << ((offset as #enum_repr) * 8);
(&r as *const #enum_repr as *const u8 as *const #name)
};
};
let is_zst = info.variants.len() == 1;
if info.variants.is_empty() {
quote! {
fn enum_into_u32(self) -> u32 {
#core::panic!(concat!(stringify!(#name), " is uninhabited."))
}
unsafe fn enum_from_u32(val: u32) -> Self {
#core::panic!(concat!(stringify!(#name), " is uninhabited."))
}
}
} else if is_zst {
let variant = &info.variants[0].name;
quote! {
fn enum_into_u32(self) -> u32 {
self as u32
}
unsafe fn enum_from_u32(val: u32) -> Self {
#name::#variant
}
}
} else if info.uses_lsb_encoding() || info.uses_msb_encoding().is_some() {
// Prepares output for MSB mode.
let process_output = if let Some(msb_repr) = info.uses_msb_encoding() {
quote! {
let r = (#msb_repr as #enum_repr) - 1 - r;
}
} else {
quote!()
};
let (names, values) = if info.bit_width() >= 1000 {
// This worsens codegen quality, but avoids creating big tables for no good reason.
let variant_bits: Vec<_> = info.variants.iter().map(|x| x.variant_bit).collect();
let variant_names: Vec<_> = info
.variants
.iter()
.map(|x| {
let variant_name = &x.name;
quote! { #name::#variant_name }
})
.collect();
(variant_names, variant_bits)
} else {
// Build a table of branches.
let mut names = Vec::new();
for i in 0..info.bit_width() {
// We create invalid transmutes for invalid branches that will never happen.
// While not very safe, this encourages the compiler to generate a transmute.
names.push(quote! {{
let r = #i as #enum_repr;
#process_output
#hint_is_transmute
r
}});
}
// Fill variants into the table.
for variant in &info.variants {
let variant_name = &variant.name;
names[variant.variant_bit as usize] = quote! { #name::#variant_name };
}
let values: Vec<u32> = (0..(names.len() as u32)).collect();
(names, values)
};
quote! {
#[inline]
fn enum_into_u32(self) -> u32 {
let r = self as #enum_repr;
#process_output
r as u32
}
unsafe fn enum_from_u32(val: u32) -> Self {
// We put these in const fields so the branches they guard aren't generated even
// on -O0
match val {
// Every valid variant value has an explicit branch. If they get optimized out,
// great. Otherwise, oh well, at least it's safe.
#(#values => #names,)*
// Default case.
_ => #core::hint::unreachable_unchecked(),
}
}
}
} else if info.uses_mask_encoding() {
let discriminants: Vec<_> = info
.variants
.iter()
.map(|x| Lit::Int(LitInt::new(x.discriminant.to_string().as_str(), Span::call_site())))
.collect();
let variant_names: Vec<_> = info.variants.iter().map(|x| x.name.clone()).collect();
quote! {
fn enum_into_u32(self) -> u32 {
(self as #enum_repr).trailing_zeros()
}
unsafe fn enum_from_u32(val: u32) -> Self {
let val: #enum_repr = 1 << (val as #enum_repr);
match val {
// Every valid variant value has an explicit branch. If they get optimized out,
// great. Otherwise, oh well, at least it's safe.
#(#discriminants => #name::#variant_names,)*
// Default case, hints to the compiler that this is a transmute.
r => {
let r = r as #enum_repr;
#hint_is_transmute
r
},
}
}
}
} else if info.uses_compact_encoding() {
let variant_bits: Vec<_> = info.variants.iter().map(|x| x.variant_bit).collect();
let variant_names: Vec<_> = info.variants.iter().map(|x| x.name.clone()).collect();
quote! {
fn enum_into_u32(self) -> u32 {
match self {
#(#name::#variant_names => #variant_bits,)*
}
}
unsafe fn enum_from_u32(val: u32) -> Self {
match val {
#(#variant_bits => #name::#variant_names,)*
_ => #core::hint::unreachable_unchecked(),
}
}
}
} else {
panic!("Unknown encoding?");
}
}
fn create_enum_const_opers(
info: &EnumSetInfo,
paths: &Paths,
repr: &SynTokenStream,
) -> SynTokenStream {
let name = &info.name;
let enumset = &paths.enumset;
let internal = &paths.internal;
let vis = &info.vis;
let value_to_bit = if info.variants.is_empty() {
quote! { 0 }
} else if info.uses_lsb_encoding() {
quote! { value as u32 }
} else if let Some(size) = info.uses_msb_encoding() {
quote! { ((#size as u32) - 1 - (value as u32)) }
} else if info.uses_mask_encoding() {
quote! { (value as i64).trailing_zeros() }
} else {
let variant_bits: Vec<_> = info.variants.iter().map(|x| x.variant_bit).collect();
let variant_names: Vec<_> = info.variants.iter().map(|x| x.name.clone()).collect();
quote! {
match value {
#(#name::#variant_names => #variant_bits,)*
}
}
};
let const_impls = match info.internal_repr() {
InternalRepr::U8
| InternalRepr::U16
| InternalRepr::U32
| InternalRepr::U64
| InternalRepr::U128 => {
quote! {
#[automatically_derived]
#[doc(hidden)]
impl __EnumSetInitHelper {
pub const fn const_only(&self, value: #name) -> #enumset::EnumSet<#name> {
#internal::set::new(1 << (#value_to_bit as #repr))
}
}
#[automatically_derived]
#[doc(hidden)]
impl __EnumSetOpHelper {
pub const fn const_union(
&self,
a: #enumset::EnumSet<#name>,
b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
#internal::set::new(#internal::set::get(a) | #internal::set::get(b))
}
pub const fn const_intersection(
&self,
a: #enumset::EnumSet<#name>,
b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
#internal::set::new(#internal::set::get(a) & #internal::set::get(b))
}
pub const fn const_symmetric_difference(
&self,
a: #enumset::EnumSet<#name>,
b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
#internal::set::new(#internal::set::get(a) ^ #internal::set::get(b))
}
pub const fn const_complement(
&self,
a: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
let mut all = #enumset::EnumSet::<#name>::all();
#internal::set::new(!#internal::set::get(a) & #internal::set::get(all))
}
}
}
}
InternalRepr::Array(size) => {
quote! {
#[automatically_derived]
#[doc(hidden)]
impl __EnumSetInitHelper {
pub const fn const_only(&self, value: #name) -> #enumset::EnumSet<#name> {
let mut repr = #internal::ArrayRepr::<{ #size }>([0; #size]);
let bit = #value_to_bit;
let (idx, bit) = (bit as usize / 64, bit % 64);
repr.0[idx] |= 1u64 << bit;
#internal::set::new(repr)
}
}
#[automatically_derived]
#[doc(hidden)]
impl __EnumSetOpHelper {
pub const fn const_union(
&self,
chain_a: #enumset::EnumSet<#name>,
chain_b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
let mut a = #internal::set::get(chain_a);
let b = #internal::set::get(chain_b);
let mut i = 0;
while i < #size {
a.0[i] |= b.0[i];
i += 1;
}
#internal::set::new(a)
}
pub const fn const_intersection(
&self,
chain_a: #enumset::EnumSet<#name>,
chain_b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
let mut a = #internal::set::get(chain_a);
let b = #internal::set::get(chain_b);
let mut i = 0;
while i < #size {
a.0[i] &= b.0[i];
i += 1;
}
#internal::set::new(a)
}
pub const fn const_symmetric_difference(
&self,
chain_a: #enumset::EnumSet<#name>,
chain_b: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
let mut a = #internal::set::get(chain_a);
let b = #internal::set::get(chain_b);
let mut i = 0;
while i < #size {
a.0[i] ^= b.0[i];
i += 1;
}
#internal::set::new(a)
}
pub const fn const_complement(
&self,
chain_a: #enumset::EnumSet<#name>,
) -> #enumset::EnumSet<#name> {
let mut a = #internal::set::get(chain_a);
let mut all = #internal::set::get(#enumset::EnumSet::<#name>::all());
let mut i = 0;
while i < #size {
a.0[i] = !a.0[i] & all.0[i];
i += 1;
}
#internal::set::new(a)
}
}
}
}
};
quote! {
#[automatically_derived]
#[doc(hidden)]
#vis struct __EnumSetInitHelper;
#[automatically_derived]
#[doc(hidden)]
#vis struct __EnumSetOpHelper;
#const_impls
#[automatically_derived]
unsafe impl #internal::EnumSetConstHelper for #name {
type ConstInitHelper = __EnumSetInitHelper;
const CONST_INIT_HELPER: __EnumSetInitHelper = __EnumSetInitHelper;
type ConstOpHelper = __EnumSetOpHelper;
const CONST_OP_HELPER: __EnumSetOpHelper = __EnumSetOpHelper;
}
}
}
+26
View File
@@ -0,0 +1,26 @@
#![recursion_limit = "256"]
mod const_eval;
mod gen;
mod plan;
extern crate proc_macro;
use proc_macro::TokenStream;
use std::fmt::Display;
use syn::{parse_macro_input, DeriveInput};
/// Helper function for emitting compile errors.
fn error<T>(span: proc_macro2::Span, message: impl Display) -> syn::Result<T> {
Err(syn::Error::new(span, message))
}
#[proc_macro_derive(EnumSetType, attributes(enumset))]
pub fn derive_enum_set_type(input: TokenStream) -> TokenStream {
let input: DeriveInput = parse_macro_input!(input);
derive_enum_set_type_0(input).unwrap_or_else(|e| e.to_compile_error().into())
}
fn derive_enum_set_type_0(input: DeriveInput) -> syn::Result<TokenStream> {
let plan = plan::plan_for_enum(input)?;
Ok(gen::generate_code(plan).into())
}
+600
View File
@@ -0,0 +1,600 @@
//! This module handles parsing the input enum type, and planning the final representation for the
//! bitset.
use crate::error;
use darling::util::SpannedValue;
use darling::FromDeriveInput;
use proc_macro2::{Ident, Span};
use std::collections::{BTreeSet, HashSet};
use syn::spanned::Spanned;
use syn::{Data, DeriveInput, Fields, Variant, Visibility};
/// Decodes the custom attributes for our custom derive.
#[derive(FromDeriveInput, Default)]
#[darling(attributes(enumset), default)]
struct EnumsetAttrs {
no_ops: bool,
no_super_impls: bool,
#[darling(default)]
map: SpannedValue<Option<String>>,
#[darling(default)]
repr: SpannedValue<Option<String>>,
#[darling(default)]
serialize_repr: SpannedValue<Option<String>>,
serialize_deny_unknown: bool,
#[darling(default)]
crate_name: Option<String>,
// legacy options
serialize_as_list: SpannedValue<bool>, // replaced with serialize_repr
serialize_as_map: SpannedValue<bool>, // replaced with serialize_repr
}
/// The internal representation of an enumset.
#[derive(Copy, Clone)]
pub enum InternalRepr {
/// internal repr: `u8`
U8,
/// internal repr: `u16`
U16,
/// internal repr: `u32`
U32,
/// internal repr: `u64`
U64,
/// internal repr: `u128`
U128,
/// internal repr: `[u64; size]`
Array(usize),
}
impl InternalRepr {
/// Determines the number of variants supported by this repr.
fn supported_variants(&self) -> usize {
match self {
InternalRepr::U8 => 8,
InternalRepr::U16 => 16,
InternalRepr::U32 => 32,
InternalRepr::U64 => 64,
InternalRepr::U128 => 128,
InternalRepr::Array(size) => size * 64,
}
}
}
/// The serde representation of the enumset.
#[derive(Copy, Clone)]
pub enum SerdeRepr {
/// serde type: `u8`
U8,
/// serde type: `u16`
U16,
/// serde type: `u32`
U32,
/// serde type: `u64`
U64,
/// serde type: `u128`
U128,
/// serde type: list of `T`
List,
/// serde type: map of `T` to `bool`
Map,
/// serde type: list of `u64`
Array,
}
impl SerdeRepr {
/// Determines the number of variants supported by this repr.
fn supported_variants(&self) -> Option<usize> {
match self {
SerdeRepr::U8 => Some(8),
SerdeRepr::U16 => Some(16),
SerdeRepr::U32 => Some(32),
SerdeRepr::U64 => Some(64),
SerdeRepr::U128 => Some(128),
SerdeRepr::List => None,
SerdeRepr::Map => None,
SerdeRepr::Array => None,
}
}
}
/// An variant in the enum set type.
pub struct EnumSetValue {
/// The name of the variant.
pub name: Ident,
/// The discriminant of the variant.
pub discriminant: i64,
/// The bit this variant is stored in.
pub variant_bit: u32,
/// The span this variant originates in.
pub span: Span,
}
/// Stores information about the enum set type.
#[allow(dead_code)]
pub struct EnumSetInfo {
/// The name of the enum.
pub name: Ident,
/// The crate name to use.
pub crate_name: Option<Ident>,
/// The numeric type to represent the `EnumSet` as in memory.
explicit_internal_repr: Option<InternalRepr>,
/// Forces the internal numeric type of the `EnumSet` to be an array.
internal_repr_force_array: bool,
/// The numeric type to serialize the enum as.
explicit_serde_repr: Option<SerdeRepr>,
/// A list of variants in the enum.
pub variants: Vec<EnumSetValue>,
/// Visbility
pub vis: Visibility,
/// The numeric type to represent the underlying enum in memory.
explicit_enum_repr: Option<Ident>,
/// The lowest encountered variant discriminant.
min_discriminant: i64,
/// The highest encountered variant discriminant.
max_discriminant: i64,
/// The highest encountered bit value.
max_variant_bit: u32,
/// The span of the highest encountered variant.
max_variant_span: Option<Span>,
/// The current variant discriminant. Used to track, e.g. `A=10,B,C`.
cur_discrim: i64,
/// A list of variant names that are already in use.
used_variant_names: HashSet<String>,
/// A list of variant discriminants that are already in use.
used_discriminants: HashSet<i64>,
/// Marks if this set uses the LSB encoding.
lsb_encoding: bool,
/// Marks if this set uses the MSB encoding.
msb_encoding: Option<i64>,
/// Marks if this set uses the mask encoding.
mask_encoding: bool,
/// Marks if this set uses the compact encoding.
compact_encoding: bool,
/// Avoid generating operator overloads on the enum type.
pub no_ops: bool,
/// Avoid generating implementations for `Clone`, `Copy`, `Eq`, and `PartialEq`.
pub no_super_impls: bool,
/// Disallow unknown bits while deserializing the enum.
pub serialize_deny_unknown: bool,
/// List of warnings for the enumset.
pub warnings: Vec<(Span, &'static str)>,
}
impl EnumSetInfo {
fn new(input: &DeriveInput, attrs: &EnumsetAttrs) -> EnumSetInfo {
EnumSetInfo {
name: input.ident.clone(),
crate_name: attrs
.crate_name
.as_ref()
.map(|x| Ident::new(x, Span::call_site())),
explicit_internal_repr: None,
internal_repr_force_array: false,
explicit_serde_repr: None,
variants: Vec::new(),
vis: input.vis.clone(),
explicit_enum_repr: None,
min_discriminant: 0,
max_discriminant: 0,
max_variant_bit: 0,
max_variant_span: None,
cur_discrim: 0,
used_variant_names: HashSet::new(),
used_discriminants: HashSet::new(),
lsb_encoding: false,
msb_encoding: None,
mask_encoding: false,
compact_encoding: false,
no_ops: attrs.no_ops,
no_super_impls: attrs.no_super_impls,
serialize_deny_unknown: attrs.serialize_deny_unknown,
warnings: vec![],
}
}
/// Explicits sets the serde representation of the enumset from a string.
fn push_serialize_repr(&mut self, span: Span, ty: &str) -> syn::Result<()> {
match ty {
"u8" => self.explicit_serde_repr = Some(SerdeRepr::U8),
"u16" => self.explicit_serde_repr = Some(SerdeRepr::U16),
"u32" => self.explicit_serde_repr = Some(SerdeRepr::U32),
"u64" => self.explicit_serde_repr = Some(SerdeRepr::U64),
"u128" => self.explicit_serde_repr = Some(SerdeRepr::U128),
"list" => self.explicit_serde_repr = Some(SerdeRepr::List),
"map" => self.explicit_serde_repr = Some(SerdeRepr::Map),
"array" => self.explicit_serde_repr = Some(SerdeRepr::Array),
_ => error(span, format!("`{ty}` is not a valid serialized representation."))?,
}
Ok(())
}
/// Explicitly sets the representation of the enumset from a string.
fn push_repr(&mut self, span: Span, ty: &str) -> syn::Result<()> {
match ty {
"u8" => self.explicit_internal_repr = Some(InternalRepr::U8),
"u16" => self.explicit_internal_repr = Some(InternalRepr::U16),
"u32" => self.explicit_internal_repr = Some(InternalRepr::U32),
"u64" => self.explicit_internal_repr = Some(InternalRepr::U64),
"u128" => self.explicit_internal_repr = Some(InternalRepr::U128),
"array" => self.internal_repr_force_array = true,
_ => error(span, format!("`{ty}` is not a valid internal enumset representation."))?,
}
Ok(())
}
/// Adds a variant to the enumset.
fn push_variant(&mut self, variant: &Variant) -> syn::Result<()> {
if variant.fields.len() as u64 > u32::MAX as u64 {
error(
variant.span(),
"You have way too many variants. enumset does not support this.",
)?;
}
if self.used_variant_names.contains(&variant.ident.to_string()) {
error(variant.span(), "Duplicated variant name.")
} else if let Fields::Unit = variant.fields {
// Parse the discriminant.
if let Some((_, expr)) = &variant.discriminant {
self.cur_discrim = crate::const_eval::eval_literal(expr)?;
}
// Validate the discriminant.
let discriminant = self.cur_discrim;
if self.used_discriminants.contains(&discriminant) {
error(variant.span(), "Duplicated enum discriminant.")?;
}
// Add the variant to the info.
self.cur_discrim += 1;
if discriminant > self.max_discriminant {
self.max_discriminant = discriminant;
}
if discriminant < self.min_discriminant {
self.min_discriminant = discriminant;
}
self.variants.push(EnumSetValue {
name: variant.ident.clone(),
discriminant,
variant_bit: !0,
span: variant.span(),
});
self.used_variant_names.insert(variant.ident.to_string());
self.used_discriminants.insert(discriminant);
Ok(())
} else {
error(variant.span(), "`#[derive(EnumSetType)]` can only be used on fieldless enums.")
}
}
/// Returns the actual internal representation of the set.
pub fn internal_repr(&self) -> InternalRepr {
match self.explicit_internal_repr {
Some(x) => x,
None => match self.max_variant_bit {
x if x < 8 && !self.internal_repr_force_array => InternalRepr::U8,
x if x < 16 && !self.internal_repr_force_array => InternalRepr::U16,
x if x < 32 && !self.internal_repr_force_array => InternalRepr::U32,
x if x < 64 && !self.internal_repr_force_array => InternalRepr::U64,
x => InternalRepr::Array((x as usize + 64) / 64),
},
}
}
/// Returns whether this enumset has an explicit internal representation.
pub fn has_explicit_repr(&self) -> bool {
self.explicit_internal_repr.is_some()
}
/// Returns the actual serde representation of the set.
pub fn serde_repr(&self) -> SerdeRepr {
match self.explicit_serde_repr {
Some(x) => x,
None => match self.max_variant_bit {
x if x < 8 => SerdeRepr::U8,
x if x < 16 => SerdeRepr::U16,
x if x < 32 => SerdeRepr::U32,
x if x < 64 => SerdeRepr::U64,
x if x < 128 => SerdeRepr::U128,
_ => SerdeRepr::Array,
},
}
}
pub fn enum_repr(&self) -> Ident {
if let Some(ident) = &self.explicit_enum_repr {
ident.clone()
} else {
if self.min_discriminant >= 0 {
match self.max_discriminant {
x if x <= u8::MAX as i64 => Ident::new("u8", Span::call_site()),
x if x <= u16::MAX as i64 => Ident::new("u16", Span::call_site()),
x if x <= u32::MAX as i64 => Ident::new("u32", Span::call_site()),
_ => Ident::new("u64", Span::call_site()),
}
} else {
match (self.max_discriminant, self.min_discriminant) {
(max, min) if max <= i8::MAX as i64 && min >= i8::MIN as i64 => {
Ident::new("i8", Span::call_site())
}
(max, min) if max <= i16::MAX as i64 && min >= i16::MIN as i64 => {
Ident::new("i16", Span::call_site())
}
(max, min) if max <= i32::MAX as i64 && min >= i32::MIN as i64 => {
Ident::new("i32", Span::call_site())
}
_ => Ident::new("i64", Span::call_site()),
}
}
}
}
/// Returns the number of bits this enumset takes.
pub fn bit_width(&self) -> u32 {
self.max_variant_bit + 1
}
/// Validate the enumset type.
fn validate(&self) -> syn::Result<()> {
// Gets the span of the maximum value.
let largest_discriminant_span = match &self.max_variant_span {
Some(x) => *x,
None => Span::call_site(),
};
// Check if all bits of the bitset can fit in the memory representation, if one was given.
if self.internal_repr().supported_variants() <= self.max_variant_bit as usize {
error(
largest_discriminant_span,
"`repr` is too small to contain the largest discriminant.",
)?;
}
// Check if all bits of the bitset can fit in the serialization representation.
if let Some(supported_variants) = self.serde_repr().supported_variants() {
if supported_variants <= self.max_variant_bit as usize {
error(
largest_discriminant_span,
"`serialize_repr` is too small to contain the largest discriminant.",
)?;
}
}
// Checks if any bits of the variant are too large.
for variant in &self.variants {
if variant.variant_bit == !0 {
panic!("Sentinel value found in enumset plan!?");
}
if variant.variant_bit >= 0xFFFFFFC0 {
error(variant.span, "Maximum variant bit allowed is `0xFFFFFFBF`.")?;
}
}
Ok(())
}
/// Returns a bitmask of all variants in the set.
pub fn variant_map(&self) -> Vec<u64> {
let mut vec = vec![0];
for variant in &self.variants {
let (idx, bit) = (variant.variant_bit as usize / 64, variant.variant_bit % 64);
while idx >= vec.len() {
vec.push(0);
}
vec[idx] |= 1u64 << bit;
}
vec
}
/// Maps the enum variants as a LSB set.
fn map_lsb(&mut self) -> syn::Result<()> {
for variant in &mut self.variants {
if variant.discriminant < 0 {
error(variant.span, "Discriminant should not be negative.")?;
}
if variant.discriminant >= 0xFFFFFFC0 {
error(variant.span, "Maximum variant bit allowed is `0xFFFFFFBF`.")?;
}
variant.variant_bit = variant.discriminant as u32;
}
self.lsb_encoding = true;
self.update_after_map();
Ok(())
}
/// Maps the enum variants as a MSB set.
fn map_msb(&mut self, span: Span) -> syn::Result<()> {
let bit_width = match self.explicit_internal_repr {
Some(InternalRepr::U8) => 8,
Some(InternalRepr::U16) => 16,
Some(InternalRepr::U32) => 32,
Some(InternalRepr::U64) => 64,
Some(InternalRepr::U128) => 128,
_ => error(
span,
"#[enumset(map = \"msb\")] can only be used with an explicit integer repr.",
)?,
};
for variant in &mut self.variants {
if variant.discriminant < 0 {
error(variant.span, "Discriminant should not be negative.")?;
}
if variant.discriminant >= bit_width {
error(variant.span, "`repr` is too small to contain this discriminant.")?;
}
variant.variant_bit = (bit_width - 1 - variant.discriminant) as u32;
}
self.msb_encoding = Some(bit_width);
self.update_after_map();
Ok(())
}
/// Maps the enum variants as a compact set.
fn map_masks(&mut self) -> syn::Result<()> {
for variant in &mut self.variants {
if variant.discriminant.count_ones() != 1 {
error(variant.span, "All variants must be a non-zero power of two.")?;
}
variant.variant_bit = variant.discriminant.trailing_zeros();
}
self.mask_encoding = true;
self.update_after_map();
Ok(())
}
/// Maps the enum variants as a compact set.
fn map_compact(&mut self) {
let mut occupied = BTreeSet::new();
for i in 0..self.variants.len() {
occupied.insert(i as u32);
}
let variant_len = self.variants.len();
for variant in &mut self.variants {
if variant.discriminant > 0 && variant.discriminant < variant_len as i64 {
variant.variant_bit = variant.discriminant as u32;
occupied.remove(&variant.variant_bit);
}
}
for variant in &mut self.variants {
if variant.variant_bit == !0 {
let first = *occupied.iter().next().unwrap();
variant.variant_bit = first;
occupied.remove(&first);
}
}
self.compact_encoding = true;
self.update_after_map();
}
/// Updates internal state after mappings are applied.
fn update_after_map(&mut self) {
self.max_variant_bit = 0;
for variant in &self.variants {
if variant.variant_bit > self.max_variant_bit {
self.max_variant_bit = variant.variant_bit;
self.max_variant_span = Some(variant.span);
}
}
}
/// Returns whether the LSB encoding is used for this set.
pub fn uses_lsb_encoding(&self) -> bool {
self.lsb_encoding
}
/// Returns whether the MSB encoding is used for this set.
pub fn uses_msb_encoding(&self) -> Option<i64> {
self.msb_encoding
}
/// Returns whether the mask encoding is used for this set.
pub fn uses_mask_encoding(&self) -> bool {
self.mask_encoding
}
/// Returns whether the compact encoding is used for this set.
pub fn uses_compact_encoding(&self) -> bool {
self.compact_encoding
}
}
pub fn plan_for_enum(input: DeriveInput) -> syn::Result<EnumSetInfo> {
let attrs: EnumsetAttrs = EnumsetAttrs::from_derive_input(&input)?;
if !input.generics.params.is_empty() {
error(
input.generics.span(),
"`#[derive(EnumSetType)]` cannot be used on enums with type parameters.",
)
} else if let Data::Enum(data) = &input.data {
let mut info = EnumSetInfo::new(&input, &attrs);
// Check enum repr
for attr in &input.attrs {
if attr.path().is_ident("repr") {
let meta: Ident = attr.parse_args()?;
let str = meta.to_string();
match str.as_str() {
"Rust" => {}
"C" => info.explicit_enum_repr = Some(Ident::new("u64", Span::call_site())),
"u8" | "u16" | "u32" | "u64" | "u128" | "usize" => {
info.explicit_enum_repr = Some(Ident::new(str.as_str(), Span::call_site()))
}
"i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {
info.explicit_enum_repr = Some(Ident::new(str.as_str(), Span::call_site()))
}
x => {
error(attr.span(), format!("`#[repr({x})]` is not supported by enumset."))?
}
}
}
}
// Parse internal representations
if let Some(repr) = &*attrs.repr {
info.push_repr(attrs.repr.span(), repr)?;
}
// Parse serialization representations
if let Some(serialize_repr) = &*attrs.serialize_repr {
info.push_serialize_repr(attrs.serialize_repr.span(), serialize_repr)?;
}
if *attrs.serialize_as_map {
info.explicit_serde_repr = Some(SerdeRepr::Map);
info.warnings.push((
attrs.serialize_as_map.span(),
"#[enumset(serialize_as_map)] is deprecated. \
Use `#[enumset(serialize_repr = \"map\")]` instead.",
));
}
if *attrs.serialize_as_list {
// in old versions, serialize_as_list will override serialize_as_map
info.explicit_serde_repr = Some(SerdeRepr::List);
info.warnings.push((
attrs.serialize_as_list.span(),
"#[enumset(serialize_as_list)] is deprecated. \
Use `#[enumset(serialize_repr = \"list\")]` instead.",
));
}
#[cfg(feature = "std_deprecation_warning")]
{
info.warnings.push((
input.span(),
"feature = \"std\" is depercated. If you rename `enumset`, use \
feature = \"proc-macro-crate\" instead. If you don't, remove the feature.",
));
}
#[cfg(feature = "serde2_deprecation_warning")]
{
info.warnings.push((
input.span(),
"feature = \"serde2\" was never valid and did nothing. Please remove the feature.",
));
}
// Parse enum variants
for variant in &data.variants {
info.push_variant(variant)?;
}
// Compact the enumset if requested
match (*attrs.map).as_deref() {
None | Some("lsb") => info.map_lsb()?,
Some("msb") => info.map_msb(attrs.map.span())?,
Some("compact") => info.map_compact(),
Some("mask") => info.map_masks()?,
Some(map) => error(attrs.map.span(), format!("`{map}` is not a valid mapping."))?,
}
// Validate the enumset
info.validate()?;
// Generates the actual `EnumSetType` implementation
Ok(info)
} else {
error(input.span(), "`#[derive(EnumSetType)]` may only be used on enums")
}
}