Lines
100 %
Functions
50 %
Branches
//! `choice` fields: option keys are exact, an empty value takes the default.
use crate::descriptor::{Field, Kind};
use crate::values::{FormValues, Row};
pub(crate) fn unknown_key(options: &[(&str, &str)], value: &str) -> Option<String> {
if options.iter().any(|(key, _)| *key == value) {
return None;
}
let keys: Vec<&str> = options.iter().map(|(key, _)| *key).collect();
Some(format!("must be one of: {}", keys.join(", ")))
/// The value a handler sees: trimmed, with a present empty value replaced by
/// the default when there is one.
fn normal<'a>(field: &Field, value: &'a str) -> &'a str {
let value = value.trim();
match field.kind {
Kind::Choice {
default: Some(default),
..
} if value.is_empty() => default,
_ => value,
fn is_choice(field: &Field) -> bool {
matches!(field.kind, Kind::Choice { .. })
impl FormValues {
/// A copy with every present `choice` value normalised; absent values stay
/// absent.
#[must_use]
pub fn normalized(&self, form: &crate::Form) -> Self {
let mut values = self.clone();
for field in form.fields {
Kind::Rows { fields, .. } => values.normalize_rows(field.key, fields),
_ if is_choice(field) => values.normalize_text(field),
_ => {}
values
fn normalize_text(&mut self, field: &Field) {
if let Some(text) = self
.text(field.key)
.map(|text| normal(field, text).to_string())
{
self.set(field.key, &text);
fn normalize_rows(&mut self, key: &str, fields: &[Field]) {
let Some(rows) = self.rows(key) else {
return;
};
let rows: Vec<Row> = rows.iter().map(|row| normal_row(fields, row)).collect();
self.replace_rows(key, rows);
fn normal_row(fields: &[Field], row: &Row) -> Row {
let mut row = row.clone();
for field in fields.iter().filter(|field| is_choice(field)) {
if let Some(text) = row.get_mut(field.key) {
*text = normal(field, text).to_string();
row