use crate::flags::{self, FlagsValue};
#[cfg(all(test, feature = "async-graphql"))]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct FlagsInput<F>(F);
impl<F> FlagsInput<F> {
#[inline]
pub const fn new(value: F) -> Self {
Self(value)
}
#[inline]
pub const fn get(&self) -> &F {
&self.0
}
#[inline]
pub fn into_inner(self) -> F {
self.0
}
}
impl<F> From<F> for FlagsInput<F> {
#[inline]
fn from(value: F) -> Self {
Self(value)
}
}
#[inline]
#[must_use]
pub fn input_name<F: FlagsValue>() -> String {
format!("{}Input", F::GRAPHQL_NAME)
}
#[must_use]
pub fn input_description<F: FlagsValue>() -> String {
format!(
"A set of `{name}` flags, written any of three ways: a LIST of flag words \
(`[\"DEFAULT\", \"FORCED\"]`), an INTEGER bit pattern (`3`), or the TEXT form — flag words \
and `0x…` tokens separated by `|` (`\"DEFAULT | FORCED\"`), of which a single word is the \
one-element case. A bit outside the declared set is refused rather than truncated, in every \
form. Rendered back as the text form. {vocabulary}.",
name = F::GRAPHQL_NAME,
vocabulary = flags::vocabulary::<F>()
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct FlagsView<F>(F);
impl<F> FlagsView<F> {
#[inline]
pub const fn new(value: F) -> Self {
Self(value)
}
#[inline]
pub const fn get(&self) -> &F {
&self.0
}
#[inline]
pub fn into_inner(self) -> F {
self.0
}
}
impl<F> From<F> for FlagsView<F> {
#[inline]
fn from(value: F) -> Self {
Self(value)
}
}
pub const FIXED_FIELDS: [&str; 11] = [
"bits",
"text",
"names",
"isEmpty",
"isAll",
"complement",
"contains",
"intersects",
"intersection",
"union",
"difference",
];
pub const SYMMETRIC_DIFFERENCE: &str = "symmetricDifference";
pub const OPERAND: &str = "other";
pub fn fixed_fields() -> impl Iterator<Item = &'static str> {
FIXED_FIELDS
.into_iter()
.chain(std::iter::once(SYMMETRIC_DIFFERENCE))
}
pub const SELF_RETURNING: [&str; 4] = [
"complement",
"intersection",
"union",
"difference",
];
#[must_use]
pub fn is_self_returning(field: &str) -> bool {
SELF_RETURNING.contains(&field) || field == SYMMETRIC_DIFFERENCE
}
#[must_use]
pub fn derive<F: FlagsValue>(value: F, field: &str, operand: F) -> Option<F> {
match field {
"complement" => Some(value.complement()),
"intersection" => Some(value.intersection(operand)),
"union" => Some(value.union(operand)),
"difference" => Some(value.difference(operand)),
_ if field == SYMMETRIC_DIFFERENCE => Some(value.symmetric_difference(operand)),
_ => None,
}
}
#[must_use]
pub fn predicate<F: FlagsValue>(value: F, field: &str, operand: F) -> Option<bool> {
match field {
"contains" => Some(value.contains(operand)),
"intersects" => Some(value.intersects(operand)),
_ => None,
}
}
#[cfg(feature = "async-graphql")]
mod wire {
use std::borrow::Cow;
use bitflags::parser::ParseHex as _;
use super::{
FlagsInput, FlagsValue, FlagsView, OPERAND, derive, fixed_fields, flags, input_description,
input_name, is_self_returning, predicate,
};
use crate::graphql::ToGraphqlOutput;
fn read<F: FlagsValue>(value: &async_graphql::Value) -> Result<F, String> {
match value {
async_graphql::Value::List(items) => {
let mut words = Vec::with_capacity(items.len());
for item in items {
let async_graphql::Value::String(word) = item else {
return Err(format!(
"the list form of a `{}` operand carries flag words as STRINGS — `{}` is not one. \
{}",
F::GRAPHQL_NAME,
item,
flags::vocabulary::<F>()
));
};
words.push(word.as_str());
}
flags::of_words::<F>(words).map_err(|refused| refusal::<F>(&refused))
}
async_graphql::Value::Number(number) => {
let Some(bits) = number.as_u64() else {
return Err(format!(
"the integer form of a `{}` operand is a NON-NEGATIVE whole number — `{number}` is \
not one. {}",
F::GRAPHQL_NAME,
flags::vocabulary::<F>()
));
};
let widened =
<F as bitflags::Flags>::Bits::parse_hex(&format!("{bits:x}")).map_err(|_| {
format!(
"`{bits}` does not fit the width `{}` is declared at. {}",
F::GRAPHQL_NAME,
flags::vocabulary::<F>()
)
})?;
flags::of_bits::<F>(widened).map_err(|refused| refusal::<F>(&refused))
}
async_graphql::Value::String(text) => {
flags::of_text::<F>(text).map_err(|refused| refusal::<F>(&refused))
}
other => Err(format!(
"a `{}` operand is a LIST of flag words, an INTEGER bit pattern, or the TEXT form — `{}` \
is none of the three. {}",
F::GRAPHQL_NAME,
other,
flags::vocabulary::<F>()
)),
}
}
fn refusal<F: FlagsValue>(refused: &flags::UnknownFlag) -> String {
format!("{refused}. {}", flags::vocabulary::<F>())
}
impl<F: FlagsValue> async_graphql::InputType for FlagsInput<F> {
type RawValueType = Self;
fn type_name() -> Cow<'static, str> {
Cow::Owned(input_name::<F>())
}
fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
registry.create_input_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
async_graphql::registry::MetaType::Scalar {
name: input_name::<F>(),
description: Some(input_description::<F>()),
is_valid: None,
visible: None,
inaccessible: false,
tags: Vec::new(),
specified_by_url: None,
directive_invocations: Vec::new(),
requires_scopes: Vec::new(),
}
})
}
fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
let value = value.unwrap_or_default();
match read::<F>(&value) {
Ok(parsed) => Ok(Self(parsed)),
Err(sentence) => Err(async_graphql::InputValueError::custom(sentence)),
}
}
fn to_value(&self) -> async_graphql::Value {
async_graphql::Value::String(flags::text(&self.0).as_str().to_owned())
}
#[inline]
fn as_raw_value(&self) -> Option<&Self::RawValueType> {
Some(self)
}
}
fn field(
name: &str,
ty: String,
args: async_graphql::indexmap::IndexMap<String, async_graphql::registry::MetaInputValue>,
) -> async_graphql::registry::MetaField {
async_graphql::registry::MetaField {
name: name.to_owned(),
description: None,
args,
ty,
deprecation: async_graphql::registry::Deprecation::NoDeprecated,
cache_control: async_graphql::CacheControl::default(),
external: false,
requires: None,
provides: None,
visible: None,
shareable: false,
inaccessible: false,
tags: Vec::new(),
override_from: None,
compute_complexity: None,
directive_invocations: Vec::new(),
requires_scopes: Vec::new(),
}
}
fn operand_argument<F: FlagsValue>(
registry: &mut async_graphql::registry::Registry,
) -> async_graphql::indexmap::IndexMap<String, async_graphql::registry::MetaInputValue> {
let mut args = async_graphql::indexmap::IndexMap::new();
args.insert(
OPERAND.to_owned(),
async_graphql::registry::MetaInputValue {
name: OPERAND.to_owned(),
description: None,
ty: <FlagsInput<F> as async_graphql::InputType>::create_type_info(registry),
deprecation: async_graphql::registry::Deprecation::NoDeprecated,
default_value: None,
visible: None,
inaccessible: false,
tags: Vec::new(),
is_secret: false,
directive_invocations: Vec::new(),
},
);
args
}
impl<F> async_graphql::resolver_utils::ContainerType for FlagsView<F>
where
F: FlagsValue,
for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
{
async fn resolve_field(
&self,
ctx: &async_graphql::Context<'_>,
) -> async_graphql::ServerResult<Option<async_graphql::Value>> {
let name = ctx.item.node.name.node.as_str();
match name {
"bits" => {
let bits = self.0.bits();
let crossed = <F::Bits as ToGraphqlOutput>::to_graphql_output(&bits);
let selection = ctx.with_selection_set(&ctx.item.node.selection_set);
return async_graphql::OutputType::resolve(&crossed, &selection, ctx.item)
.await
.map(Some);
}
"text" => {
return Ok(Some(async_graphql::Value::String(
flags::text(&self.0).as_str().to_owned(),
)));
}
"names" => {
return Ok(Some(async_graphql::Value::List(
flags::names(&self.0)
.into_iter()
.map(|word| async_graphql::Value::String(word.as_str().to_owned()))
.collect(),
)));
}
"isEmpty" => return Ok(Some(async_graphql::Value::Boolean(self.0.is_empty()))),
"isAll" => return Ok(Some(async_graphql::Value::Boolean(self.0.is_all()))),
_ => {}
}
if let Some(bit) = flags::bits::<F>().find(|bit| bit.field == name) {
return Ok(Some(async_graphql::Value::Boolean(
self.0.contains(bit.value),
)));
}
let operand = if name == "complement" {
F::empty()
} else if is_self_returning(name) || matches!(name, "contains" | "intersects") {
ctx
.param_value::<FlagsInput<F>>(OPERAND, None)
.map(|(_, operand)| operand.into_inner())?
} else {
return Ok(None);
};
if let Some(answer) = predicate(self.0, name, operand) {
return Ok(Some(async_graphql::Value::Boolean(answer)));
}
let Some(derived) = derive(self.0, name, operand) else {
return Ok(None);
};
let selection = ctx.with_selection_set(&ctx.item.node.selection_set);
async_graphql::OutputType::resolve(&FlagsView(derived), &selection, ctx.item)
.await
.map(Some)
}
}
impl<F> async_graphql::OutputType for FlagsView<F>
where
F: FlagsValue,
for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
{
#[inline]
fn type_name() -> Cow<'static, str> {
Cow::Borrowed(F::GRAPHQL_NAME)
}
fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
registry.create_output_type::<Self, _>(
async_graphql::registry::MetaTypeId::Object,
|registry| {
let boolean = <bool as async_graphql::OutputType>::create_type_info(registry);
let string = <String as async_graphql::OutputType>::create_type_info(registry);
let list = <Vec<String> as async_graphql::OutputType>::create_type_info(registry);
let bits = <<F::Bits as ToGraphqlOutput>::Output<'static> as async_graphql::OutputType>
::create_type_info(registry);
let object = format!("{}!", F::GRAPHQL_NAME);
let operand = operand_argument::<F>(registry);
let mut fields = async_graphql::indexmap::IndexMap::new();
for name in fixed_fields() {
let (ty, args) = match name {
"bits" => (bits.clone(), async_graphql::indexmap::IndexMap::new()),
"text" => (string.clone(), async_graphql::indexmap::IndexMap::new()),
"names" => (list.clone(), async_graphql::indexmap::IndexMap::new()),
"isEmpty" | "isAll" => (boolean.clone(), async_graphql::indexmap::IndexMap::new()),
"complement" => (object.clone(), async_graphql::indexmap::IndexMap::new()),
"contains" | "intersects" => (boolean.clone(), operand.clone()),
_ => (object.clone(), operand.clone()),
};
fields.insert(name.to_owned(), field(name, ty, args));
}
for bit in flags::bits::<F>() {
fields.insert(
bit.field.to_owned(),
field(
bit.field,
boolean.clone(),
async_graphql::indexmap::IndexMap::new(),
),
);
}
async_graphql::registry::MetaType::Object {
name: F::GRAPHQL_NAME.to_owned(),
description: None,
fields,
cache_control: async_graphql::CacheControl::default(),
extends: false,
shareable: false,
resolvable: true,
keys: None,
visible: None,
inaccessible: false,
interface_object: false,
tags: Vec::new(),
is_subscription: false,
rust_typename: Some(std::any::type_name::<Self>()),
directive_invocations: Vec::new(),
requires_scopes: Vec::new(),
}
},
)
}
async fn resolve(
&self,
ctx: &async_graphql::ContextSelectionSet<'_>,
_field: &async_graphql::Positioned<async_graphql::parser::types::Field>,
) -> async_graphql::ServerResult<async_graphql::Value> {
async_graphql::resolver_utils::resolve_container(ctx, self).await
}
}
impl<F> async_graphql::ObjectType for FlagsView<F>
where
F: FlagsValue,
for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
{
}
}