use bitflags::Flags;
use crate::names::{folded, lower_camel};
use crate::node::{Unbuilt, read_scalar};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;
use crate::variant::Variant;
pub fn read_flags<F>(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<F, Unbuilt>
where
F: Flags + Copy,
F::Bits: Into<u128>,
{
read_scalar(raw, path, problems, "a set of flags", |text| {
let defined = F::iter_defined_names().collect::<Vec<_>>();
let shown = || {
defined
.iter()
.map(|(name, _)| lower_camel(name))
.collect::<Vec<_>>()
.join(", ")
};
let mut value = F::empty();
let mut given = false;
for part in text.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let read = folded(part);
let Some((_, flag)) = defined.iter().find(|(name, _)| folded(name) == read) else {
return Err(format!("unknown value; possible values: {}", shown()));
};
value = value.union(*flag);
given = true;
}
if !given {
return Err(format!("no flags are given; possible values: {}", shown()));
}
Ok(value)
})
}
pub fn write_flags<F>(value: &F) -> String
where
F: Flags,
F::Bits: Into<u128>,
{
if let Some(name) = value.iter_equal_names().next() {
return lower_camel(name);
}
let mut names = value.iter_names();
let mut text = String::new();
for (name, _) in names.by_ref() {
if !text.is_empty() {
text.push(',');
}
text.push_str(&lower_camel(name));
}
let rest = names.remaining();
if !rest.is_empty() {
let unnamed = rest.bits().into();
if !text.is_empty() {
text.push(',');
}
text.push_str(&unnamed.to_string());
}
text
}
pub fn flag_variants<F>() -> Vec<Variant>
where
F: Flags,
F::Bits: Into<u128>,
{
F::iter_defined_names()
.map(|(name, flag)| Variant::Flag(name, flag.bits().into()))
.collect()
}
pub fn first_flag<F>() -> Option<F>
where
F: Flags,
{
F::iter_defined_names().next().map(|(_, flag)| flag)
}
#[macro_export]
macro_rules! flags {
($($ty:ty),+ $(,)?) => {$(
impl $crate::Node for $ty {
fn read(
raw: &$crate::Raw,
path: &$crate::Path,
problems: &mut $crate::Problems,
) -> ::core::result::Result<Self, $crate::Unbuilt> {
$crate::read_flags(raw, path, problems)
}
fn overlay(
&mut self,
raw: &$crate::Raw,
path: &$crate::Path,
problems: &mut $crate::Problems,
) -> ::core::result::Result<(), $crate::Unbuilt> {
*self = <Self as $crate::Node>::read(raw, path, problems)?;
::core::result::Result::Ok(())
}
fn shape(&self) -> $crate::Shape<'_> {
$crate::Shape::Scalar($crate::write_flags(self))
}
fn variants(&self) -> ::std::vec::Vec<$crate::Variant> {
$crate::flag_variants::<Self>()
}
fn sample() -> ::core::option::Option<Self> {
$crate::first_flag()
}
}
)+};
}
#[cfg(test)]
mod tests {
use bitflags::bitflags;
use super::{first_flag, flag_variants, read_flags, write_flags};
use crate::node::{Node, Shape};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;
use crate::variant::Variant;
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct Lab: u8 {
const None = 0;
const One = 1;
const Two = 2;
const Four = 4;
const All = 7;
}
}
flags!(Lab);
fn read<T>(text: &str) -> Result<T, String>
where
T: Node + Copy,
T: bitflags::Flags<Bits: Into<u128>>,
{
let raw = Raw::scalar(text, crate::mark::Mark::Model);
let mut problems = Problems::new();
match read_flags::<T>(&raw, &Path::new(), &mut problems) {
Ok(value) => Ok(value),
Err(_) => Err(problems.to_string()),
}
}
fn text_of(shape: Shape<'_>) -> Option<String> {
match shape {
Shape::Scalar(text) => Some(text),
_ => None,
}
}
#[test]
fn reads_names_joined_by_commas() {
let cases = [
("one,four", Lab::One | Lab::Four),
(" two , four ", Lab::Two | Lab::Four),
("ALL", Lab::All),
("one,one", Lab::One),
("Two,One", Lab::One | Lab::Two),
("none,one", Lab::One),
("NONE", Lab::empty()),
];
for (text, expected) in cases {
assert_eq!(read::<Lab>(text), Ok(expected), "read {text:?}");
}
}
#[test]
fn rejects_unknown_names_and_empty_lists() {
assert_eq!(
read::<Lab>("purple").unwrap_err(),
"\"purple\" is not a set of flags: unknown value; possible values: none, one, two, four, all"
);
let unknown = read::<Lab>("one,purple").unwrap_err();
assert!(
unknown.starts_with("\"one,purple\" is not a set of flags"),
"{unknown}"
);
for text in [
"",
",",
" , ",
"one purple",
"one-four",
"one|four",
"5",
"0x5",
] {
let error = read::<Lab>(text).unwrap_err();
assert!(error.contains("is not a set of flags"), "{text:?}: {error}");
}
for text in ["", ",", " , "] {
let error = read::<Lab>(text).unwrap_err();
assert!(error.contains("no flags are given"), "{text:?}: {error}");
}
}
#[test]
fn writes_names_in_declaration_order() {
let cases = [
(Lab::One | Lab::Four, "one,four"),
(Lab::Four | Lab::One, "one,four"),
(Lab::All, "all"),
(Lab::One, "one"),
(Lab::empty(), "none"),
(Lab::One | Lab::from_bits_retain(8), "one,8"),
(Lab::from_bits_retain(24), "24"),
];
for (value, expected) in cases {
assert_eq!(write_flags(&value), expected, "write {value:?}");
assert_eq!(text_of(value.shape()).as_deref(), Some(expected));
}
}
#[test]
fn hints_carry_weights_and_sample_is_the_first_flag() {
assert_eq!(first_flag::<Lab>(), Some(Lab::None));
assert_eq!(
flag_variants::<Lab>(),
[
Variant::Flag("None", 0),
Variant::Flag("One", 1),
Variant::Flag("Two", 2),
Variant::Flag("Four", 4),
Variant::Flag("All", 7),
]
);
assert_eq!(<Lab as Node>::sample(), Some(Lab::None));
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct NoZero: u16 {
const First = 1;
const Second = 2;
}
}
flags!(NoZero);
#[test]
fn zero_without_a_name_is_written_as_empty_text() {
assert_eq!(write_flags(&NoZero::empty()), "");
assert_eq!(write_flags(&NoZero::all()), "first,second");
assert_eq!(first_flag::<NoZero>(), Some(NoZero::First));
assert_eq!(read::<NoZero>("first,second"), Ok(NoZero::all()));
}
}