1use std::fmt;
9use std::path::PathBuf;
10
11use fig::{ExtKind, Value};
12
13use crate::consequence::Consequence;
14use crate::path::{PathPat, Seg};
15use crate::present::Presentation;
16use crate::vocab::{Validate, Validation};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum FieldType {
26 Null,
27 Bool,
28 Int,
29 Float,
30 Str,
31 Ref,
33 Extended(ExtKind),
38 Map,
39 Seq,
40}
41
42impl FieldType {
43 pub fn of(value: &Value) -> FieldType {
52 match value {
53 Value::Null => FieldType::Null,
54 Value::Bool(_) => FieldType::Bool,
55 Value::Int(_) | Value::Uint(_) => FieldType::Int,
56 Value::Float(_) => FieldType::Float,
57 Value::Str(_) => FieldType::Str,
58 Value::Extended { kind, .. } => FieldType::Extended(*kind),
59 Value::Seq(_) => FieldType::Seq,
60 Value::Map(_) => FieldType::Map,
61 }
62 }
63
64 pub fn admits(self, value: &Value) -> bool {
90 if self.admits_item(value) {
91 return true;
92 }
93 match value {
94 Value::Seq(items) => items.iter().all(|item| self.admits_item(item)),
95 _ => false,
96 }
97 }
98
99 fn admits_item(self, value: &Value) -> bool {
102 let found = FieldType::of(value);
103 match self {
104 FieldType::Float => matches!(found, FieldType::Float | FieldType::Int),
105 FieldType::Ref => found == FieldType::Str,
106 FieldType::Extended(kind) => match value {
107 Value::Str(text) => extended_text_fits(kind, text),
108 _ => found == self,
109 },
110 expected => found == expected,
111 }
112 }
113
114 pub fn coerce(self, s: &str) -> Value {
125 let t = s.trim();
126 match self {
127 FieldType::Null => match t {
130 "" | "~" => Value::Null,
131 _ if t.eq_ignore_ascii_case("null") => Value::Null,
132 _ => Value::Str(s.to_string()),
133 },
134 FieldType::Bool => match t.to_ascii_lowercase().as_str() {
139 "true" | "yes" | "on" => Value::Bool(true),
140 "false" | "no" | "off" => Value::Bool(false),
141 _ => Value::Str(s.to_string()),
142 },
143 FieldType::Int => match Value::parse_number(t, false) {
148 Ok(v) if !v.is_f64() => v,
149 _ => Value::Str(s.to_string()),
150 },
151 FieldType::Float => {
156 Value::parse_number(t, true).unwrap_or_else(|_| Value::Str(s.to_string()))
157 }
158 FieldType::Extended(kind) => {
159 if extended_text_fits(kind, t) {
160 Value::Extended {
161 kind,
162 text: t.to_string(),
163 }
164 } else {
165 Value::Str(s.to_string())
166 }
167 }
168 FieldType::Str | FieldType::Ref | FieldType::Map | FieldType::Seq => {
171 Value::Str(s.to_string())
172 }
173 }
174 }
175}
176
177const NAMES: &[(&str, FieldType)] = &[
187 ("null", FieldType::Null),
188 ("bool", FieldType::Bool),
189 ("int", FieldType::Int),
190 ("float", FieldType::Float),
191 ("str", FieldType::Str),
192 ("ref", FieldType::Ref),
193 ("date", FieldType::Extended(ExtKind::LocalDate)),
194 ("datetime", FieldType::Extended(ExtKind::OffsetDateTime)),
195 (
196 "local-datetime",
197 FieldType::Extended(ExtKind::LocalDateTime),
198 ),
199 ("time", FieldType::Extended(ExtKind::LocalTime)),
200 ("enum", FieldType::Extended(ExtKind::EnumLiteral)),
201 ("char", FieldType::Extended(ExtKind::CharLiteral)),
202 ("map", FieldType::Map),
203 ("seq", FieldType::Seq),
204];
205
206impl FieldType {
207 pub fn from_name(name: &str) -> Option<FieldType> {
221 NAMES
222 .iter()
223 .find(|(known, _)| *known == name)
224 .map(|(_, ty)| *ty)
225 }
226
227 pub fn suggest_name(name: &str) -> Option<&'static str> {
233 let lower = name.to_ascii_lowercase();
234 Some(match lower.as_str() {
235 "string" | "text" => "str",
236 "boolean" => "bool",
237 "integer" | "i64" | "u64" => "int",
238 "number" | "f64" | "double" => "float",
239 "list" | "array" | "sequence" => "seq",
240 "object" | "dict" | "mapping" | "table" => "map",
241 "reference" | "link" => "ref",
242 "local-date" => "date",
243 "offset-datetime" => "datetime",
244 "local-time" => "time",
245 _ => {
246 return NAMES
247 .iter()
248 .map(|(known, _)| *known)
249 .find(|known| *known == lower);
250 }
251 })
252 }
253}
254
255impl fmt::Display for FieldType {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 if let Some((name, _)) = NAMES.iter().find(|(_, ty)| ty == self) {
263 return f.write_str(name);
264 }
265 f.write_str(match self {
266 FieldType::Extended(ExtKind::NumberSpecial) => "number-special",
267 FieldType::Extended(ExtKind::PlistDate) => "plist-date",
268 FieldType::Extended(ExtKind::Data) => "data",
269 _ => "extended",
271 })
272 }
273}
274
275fn extended_text_fits(kind: ExtKind, text: &str) -> bool {
282 if text.is_empty() {
283 return false;
284 }
285 match kind {
286 ExtKind::OffsetDateTime
288 | ExtKind::LocalDateTime
289 | ExtKind::LocalDate
290 | ExtKind::LocalTime => text.chars().all(|c| {
291 c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | '+' | 'T' | 't' | 'Z' | 'z' | ' ')
292 }),
293 ExtKind::EnumLiteral => {
295 let mut chars = text.chars();
296 chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
297 && chars.all(|c| c.is_alphanumeric() || c == '_')
298 }
299 ExtKind::CharLiteral => text.chars().all(|c| c.is_ascii_digit()),
301 ExtKind::NumberSpecial => matches!(
302 text,
303 "Infinity" | "-Infinity" | "+Infinity" | "NaN" | "-NaN" | "+NaN"
304 ),
305 _ => true,
310 }
311}
312
313#[derive(Debug, Clone)]
332#[non_exhaustive]
333pub struct FieldRule<C> {
334 pub at: PathPat,
336 pub ty: Option<FieldType>,
338 pub constraint: Option<C>,
340 pub present: Presentation,
342 pub on_change: Vec<Consequence>,
348 pub origin: Option<Origin>,
351}
352
353#[derive(Debug, Clone, PartialEq, Eq)]
365#[non_exhaustive]
366pub struct Origin {
367 pub document: PathBuf,
370 pub at: String,
374}
375
376impl Origin {
377 pub fn new(document: impl Into<PathBuf>, at: impl Into<String>) -> Self {
379 Self {
380 document: document.into(),
381 at: at.into(),
382 }
383 }
384}
385
386impl fmt::Display for Origin {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 write!(f, "{} {}", self.document.display(), self.at)
390 }
391}
392
393impl<C> FieldRule<C> {
394 pub fn new(at: PathPat) -> Self {
397 Self {
398 at,
399 ty: None,
400 constraint: None,
401 present: Presentation::default(),
402 on_change: Vec::new(),
403 origin: None,
404 }
405 }
406
407 pub fn ty(mut self, ty: impl Into<Option<FieldType>>) -> Self {
411 self.ty = ty.into();
412 self
413 }
414
415 pub fn constraint(mut self, constraint: C) -> Self {
422 self.constraint = Some(constraint);
423 self
424 }
425
426 pub fn constraint_opt(mut self, constraint: Option<C>) -> Self {
429 self.constraint = constraint;
430 self
431 }
432
433 pub fn present(mut self, present: Presentation) -> Self {
435 self.present = present;
436 self
437 }
438
439 pub fn on_change(mut self, consequence: Consequence) -> Self {
443 self.on_change.push(consequence);
444 self
445 }
446
447 pub fn on_change_all(mut self, consequences: Vec<Consequence>) -> Self {
450 self.on_change = consequences;
451 self
452 }
453
454 pub fn origin(mut self, origin: Origin) -> Self {
457 self.origin = Some(origin);
458 self
459 }
460
461 pub fn map_constraint<D>(self, f: impl FnOnce(C) -> D) -> FieldRule<D> {
466 FieldRule {
467 at: self.at,
468 ty: self.ty,
469 constraint: self.constraint.map(f),
470 present: self.present,
471 on_change: self.on_change,
472 origin: self.origin,
473 }
474 }
475}
476
477impl<C: Validate> FieldRule<C> {
478 pub fn validate(&self, value: &Value) -> Validation {
481 match &self.constraint {
482 Some(c) => c.validate(value),
483 None => Validation::Ok,
484 }
485 }
486}
487
488#[derive(Debug, Clone)]
491pub struct Schema<C> {
492 rules: Vec<FieldRule<C>>,
493}
494
495impl<C> Default for Schema<C> {
496 fn default() -> Self {
497 Self { rules: Vec::new() }
498 }
499}
500
501impl<C> Schema<C> {
502 pub fn new(rules: Vec<FieldRule<C>>) -> Self {
504 Self { rules }
505 }
506
507 pub fn rules(&self) -> &[FieldRule<C>] {
509 &self.rules
510 }
511
512 pub fn into_rules(self) -> Vec<FieldRule<C>> {
515 self.rules
516 }
517
518 pub fn map_constraints<D>(self, mut f: impl FnMut(C) -> D) -> Schema<D> {
521 Schema {
522 rules: self
523 .rules
524 .into_iter()
525 .map(|rule| rule.map_constraint(&mut f))
526 .collect(),
527 }
528 }
529
530 pub fn is_empty(&self) -> bool {
532 self.rules.is_empty()
533 }
534
535 pub fn rule_for(&self, path: &[Seg]) -> Option<&FieldRule<C>> {
538 self.rules.iter().find(|r| r.at.matches(path))
539 }
540
541 pub fn rules_for<'s, 'p: 's>(
547 &'s self,
548 path: &'p [Seg],
549 ) -> impl Iterator<Item = &'s FieldRule<C>> + 's {
550 self.rules.iter().filter(move |r| r.at.matches(path))
551 }
552}
553
554#[cfg(test)]
555mod tests {
556 use super::*;
557 use crate::vocab::Issue;
558
559 #[test]
560 fn type_directed_parse_keeps_a_string_field_a_string() {
561 assert_eq!(FieldType::Str.coerce("123"), Value::Str("123".into()));
562 assert_eq!(FieldType::Int.coerce("123"), Value::Int(123));
563 assert_eq!(FieldType::Bool.coerce("true"), Value::Bool(true));
564 assert_eq!(FieldType::Int.coerce("abc"), Value::Str("abc".into()));
566 }
567
568 #[test]
569 fn a_null_field_keeps_text_it_cannot_read_as_null() {
570 assert_eq!(FieldType::Null.coerce(""), Value::Null);
571 assert_eq!(FieldType::Null.coerce("null"), Value::Null);
572 assert_eq!(FieldType::Null.coerce("NULL"), Value::Null);
573 assert_eq!(FieldType::Null.coerce("~"), Value::Null);
574 assert_eq!(
576 FieldType::Null.coerce("important data"),
577 Value::Str("important data".into())
578 );
579 }
580
581 #[test]
582 fn a_bool_field_accepts_the_yaml_spellings() {
583 for yes in ["true", "True", "TRUE", "yes", "Yes", "on"] {
584 assert_eq!(FieldType::Bool.coerce(yes), Value::Bool(true), "{yes}");
585 }
586 for no in ["false", "False", "FALSE", "no", "No", "off"] {
587 assert_eq!(FieldType::Bool.coerce(no), Value::Bool(false), "{no}");
588 }
589 assert_eq!(FieldType::Bool.coerce("maybe"), Value::Str("maybe".into()));
590 }
591
592 #[test]
593 fn a_float_field_reads_back_the_spellings_fig_writes() {
594 let inf = FieldType::Float.coerce(".inf");
598 assert!(matches!(inf, Value::Float(f) if f.is_infinite() && f.is_sign_positive()));
599 let neg = FieldType::Float.coerce("-.inf");
600 assert!(matches!(neg, Value::Float(f) if f.is_infinite() && f.is_sign_negative()));
601 assert!(matches!(FieldType::Float.coerce(".nan"), Value::Float(f) if f.is_nan()));
602 assert!(matches!(FieldType::Float.coerce("inf"), Value::Float(f) if f.is_infinite()));
604 assert_eq!(FieldType::Float.coerce("1.5"), Value::Float(1.5));
605 assert_eq!(FieldType::Float.coerce("nope"), Value::Str("nope".into()));
606 }
607
608 #[test]
609 fn an_int_field_does_not_widen_to_a_float() {
610 assert_eq!(FieldType::Int.coerce("3"), Value::Int(3));
614 assert_eq!(FieldType::Int.coerce("3.5"), Value::Str("3.5".into()));
615 assert_eq!(
617 FieldType::Int.coerce("9223372036854775808"),
618 Value::Uint(9_223_372_036_854_775_808)
619 );
620 }
621
622 #[test]
623 fn an_extended_field_keeps_its_native_type() {
624 let ty = FieldType::Extended(ExtKind::LocalDate);
625 assert_eq!(
626 ty.coerce("1979-05-27"),
627 Value::Extended {
628 kind: ExtKind::LocalDate,
629 text: "1979-05-27".into(),
630 }
631 );
632 assert_eq!(ty.coerce("not a date"), Value::Str("not a date".into()));
635 assert_eq!(ty.coerce(""), Value::Str("".into()));
636 }
637
638 #[test]
639 fn extended_shape_guard_covers_every_kind() {
640 assert!(extended_text_fits(
641 ExtKind::OffsetDateTime,
642 "1979-05-27T07:32:00Z"
643 ));
644 assert!(extended_text_fits(ExtKind::LocalTime, "07:32:00.999"));
645 assert!(extended_text_fits(ExtKind::EnumLiteral, "foo_bar"));
646 assert!(!extended_text_fits(ExtKind::EnumLiteral, "9lives"));
647 assert!(!extended_text_fits(ExtKind::EnumLiteral, "has space"));
648 assert!(extended_text_fits(ExtKind::CharLiteral, "97"));
649 assert!(!extended_text_fits(ExtKind::CharLiteral, "a"));
650 assert!(extended_text_fits(ExtKind::NumberSpecial, "-Infinity"));
651 assert!(!extended_text_fits(ExtKind::NumberSpecial, "inf"));
652 }
653
654 #[derive(Debug, Clone)]
657 struct AlwaysReject;
658 impl Validate for AlwaysReject {
659 fn validate(&self, _value: &Value) -> Validation {
660 Validation::Reject(Issue::custom("", "no"))
661 }
662 }
663
664 #[test]
665 fn rule_validate_dispatches_to_the_embedder_constraint() {
666 let rule = FieldRule::new(PathPat::key("status"))
667 .ty(FieldType::Str)
668 .constraint(AlwaysReject);
669 assert!(rule.validate(&Value::Str("anything".into())).is_reject());
670 }
671
672 #[test]
673 fn rule_with_no_constraint_always_validates_ok() {
674 let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"));
675 assert_eq!(
676 rule.validate(&Value::Str("anything".into())),
677 Validation::Ok
678 );
679 }
680
681 #[test]
682 fn schema_rule_for_finds_first_match_in_declaration_order() {
683 let schema = Schema::new(vec![
684 FieldRule::new(PathPat::each_item_of("tags"))
685 .ty(FieldType::Str)
686 .constraint_opt(None::<AlwaysReject>),
687 FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
688 ]);
689 assert!(schema.rule_for(&[Seg::Key("title".into())]).is_some());
690 assert!(
691 schema
692 .rule_for(&[Seg::Key("tags".into()), Seg::Index(0)])
693 .is_some()
694 );
695 assert!(schema.rule_for(&[Seg::Key("missing".into())]).is_none());
696 }
697
698 #[test]
699 fn every_value_has_a_type_and_uint_is_an_int() {
700 assert_eq!(FieldType::of(&Value::Null), FieldType::Null);
701 assert_eq!(FieldType::of(&Value::Bool(true)), FieldType::Bool);
702 assert_eq!(FieldType::of(&Value::Int(1)), FieldType::Int);
703 assert_eq!(FieldType::of(&Value::Uint(u64::MAX)), FieldType::Int);
704 assert_eq!(FieldType::of(&Value::Float(1.5)), FieldType::Float);
705 assert_eq!(FieldType::of(&Value::Str("x".into())), FieldType::Str);
706 assert_eq!(
707 FieldType::of(&Value::Extended {
708 kind: ExtKind::LocalDate,
709 text: "1979-05-27".into()
710 }),
711 FieldType::Extended(ExtKind::LocalDate)
712 );
713 assert_eq!(FieldType::of(&Value::Seq(vec![])), FieldType::Seq);
714 assert_eq!(FieldType::of(&Value::Map(vec![])), FieldType::Map);
715 }
716
717 #[test]
718 fn admits_is_equality_plus_the_two_widenings() {
719 let text = Value::Str("123".into());
720 assert!(FieldType::Str.admits(&text));
721 assert!(FieldType::Ref.admits(&text));
723 assert!(!FieldType::Int.admits(&text));
725
726 assert!(FieldType::Float.admits(&Value::Int(3)));
728 assert!(FieldType::Float.admits(&Value::Uint(u64::MAX)));
729 assert!(FieldType::Float.admits(&Value::Float(0.5)));
730 assert!(!FieldType::Int.admits(&Value::Float(3.0)));
732 assert!(FieldType::Int.admits(&Value::Uint(u64::MAX)));
733
734 assert!(FieldType::Null.admits(&Value::Null));
735 assert!(!FieldType::Str.admits(&Value::Null));
736 assert!(FieldType::Bool.admits(&Value::Bool(false)));
737 assert!(FieldType::Seq.admits(&Value::Seq(vec![])));
738 assert!(!FieldType::Seq.admits(&Value::Map(vec![])));
739 assert!(FieldType::Map.admits(&Value::Map(vec![])));
740 }
741
742 #[test]
743 fn an_extended_field_admits_its_own_kind_and_a_string_shaped_like_one() {
744 let date = Value::Extended {
745 kind: ExtKind::LocalDate,
746 text: "1979-05-27".into(),
747 };
748 let date_field = FieldType::Extended(ExtKind::LocalDate);
749 assert!(date_field.admits(&date));
750 assert!(!FieldType::Extended(ExtKind::LocalTime).admits(&date));
751 assert!(!FieldType::Str.admits(&date));
752 assert!(date_field.admits(&Value::Str("1979-05-27".into())));
756 assert!(!date_field.admits(&Value::Str("yesterday".into())));
758 assert!(!date_field.admits(&Value::Str("".into())));
759 assert!(!date_field.admits(&Value::Int(1979)));
760 }
761
762 #[test]
763 fn a_type_admits_a_list_of_its_items_one_level_deep() {
764 let strings = Value::Seq(vec![Value::Str("a".into()), Value::Str("b".into())]);
765 assert!(FieldType::Str.admits(&strings));
766 assert!(FieldType::Ref.admits(&strings));
767 assert!(!FieldType::Int.admits(&strings));
768 let nested = Value::Seq(vec![strings.clone()]);
770 assert!(!FieldType::Str.admits(&nested));
771 assert!(FieldType::Seq.admits(&nested));
772 let mixed = Value::Seq(vec![Value::Str("a".into()), Value::Int(1)]);
774 assert!(!FieldType::Str.admits(&mixed));
775 assert!(!FieldType::Float.admits(&mixed));
776 assert!(FieldType::Str.admits(&Value::Seq(vec![])));
777 assert!(FieldType::Float.admits(&Value::Seq(vec![Value::Int(1), Value::Float(0.5)])));
779 assert!(
780 FieldType::Extended(ExtKind::LocalDate)
781 .admits(&Value::Seq(vec![Value::Str("1979-05-27".into())]))
782 );
783 }
784
785 #[test]
786 fn a_type_displays_as_the_format_spells_it_and_reads_back() {
787 assert_eq!(FieldType::Int.to_string(), "int");
788 assert_eq!(FieldType::Str.to_string(), "str");
789 assert_eq!(FieldType::Seq.to_string(), "seq");
790 assert_eq!(FieldType::Extended(ExtKind::LocalDate).to_string(), "date");
792 assert_eq!(
793 FieldType::Extended(ExtKind::OffsetDateTime).to_string(),
794 "datetime"
795 );
796 assert_eq!(
797 FieldType::Extended(ExtKind::LocalDateTime).to_string(),
798 "local-datetime"
799 );
800 assert_eq!(FieldType::Extended(ExtKind::LocalTime).to_string(), "time");
801 assert_eq!(
802 FieldType::Extended(ExtKind::EnumLiteral).to_string(),
803 "enum"
804 );
805 assert_eq!(
806 FieldType::Extended(ExtKind::CharLiteral).to_string(),
807 "char"
808 );
809 assert_eq!(
811 FieldType::Extended(ExtKind::NumberSpecial).to_string(),
812 "number-special"
813 );
814 for (name, ty) in NAMES {
816 assert_eq!(FieldType::from_name(name), Some(*ty), "{name}");
817 assert_eq!(ty.to_string(), *name, "{ty:?}");
818 }
819 assert_eq!(FieldType::from_name("number-special"), None);
820 assert_eq!(FieldType::from_name("string"), None);
821 }
822
823 #[test]
824 fn a_misspelled_type_name_gets_the_one_meant() {
825 assert_eq!(FieldType::suggest_name("string"), Some("str"));
826 assert_eq!(FieldType::suggest_name("String"), Some("str"));
827 assert_eq!(FieldType::suggest_name("Int"), Some("int"));
828 assert_eq!(FieldType::suggest_name("boolean"), Some("bool"));
829 assert_eq!(FieldType::suggest_name("local-date"), Some("date"));
830 assert_eq!(FieldType::suggest_name("array"), Some("seq"));
831 assert_eq!(FieldType::suggest_name("wibble"), None);
832 }
833
834 #[test]
835 fn a_rule_can_say_where_it_came_from_and_change_its_constraint_type() {
836 let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"))
837 .ty(FieldType::Str)
838 .constraint(AlwaysReject)
839 .origin(Origin::new("schema.figl", "rules[0]"));
840 assert_eq!(
841 rule.origin.as_ref().map(ToString::to_string),
842 Some("schema.figl rules[0]".to_owned())
843 );
844 assert_eq!(
846 FieldRule::<AlwaysReject>::new(PathPat::key("x")).origin,
847 None
848 );
849 let mapped: FieldRule<&'static str> = rule.map_constraint(|_| "mine");
851 assert_eq!(mapped.constraint, Some("mine"));
852 assert_eq!(mapped.ty, Some(FieldType::Str));
853 assert!(mapped.origin.is_some());
854
855 let schema = Schema::new(vec![
856 FieldRule::new(PathPat::key("a")).constraint(AlwaysReject),
857 ]);
858 let mapped = schema.map_constraints(|_| 1u8);
859 assert_eq!(mapped.rules()[0].constraint, Some(1));
860 assert_eq!(mapped.into_rules().len(), 1);
861 }
862
863 #[test]
864 fn rules_for_lists_every_match_with_rule_for_first() {
865 let schema = Schema::new(vec![
866 FieldRule::new(PathPat(vec![
867 crate::SegPat::Key("meta".into()),
868 crate::SegPat::Key("id".into()),
869 ]))
870 .ty(FieldType::Int)
871 .constraint_opt(None::<AlwaysReject>),
872 FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
873 FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
874 FieldRule::new(PathPat(vec![crate::SegPat::AnyDepth])).ty(FieldType::Null),
875 ]);
876 let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
877 let matched: Vec<_> = schema.rules_for(&id).map(|r| r.ty).collect();
878 assert_eq!(
881 matched,
882 vec![
883 Some(FieldType::Int),
884 Some(FieldType::Str),
885 Some(FieldType::Null)
886 ]
887 );
888 assert_eq!(schema.rule_for(&id).unwrap().ty, matched[0]);
889 assert_eq!(schema.rules_for(&[Seg::Key("nothing".into())]).count(), 1);
890 }
891
892 #[test]
893 fn a_specific_rule_takes_precedence_over_a_subtree_rule() {
894 let schema = Schema::new(vec![
895 FieldRule::new(PathPat(vec![
896 crate::SegPat::Key("meta".into()),
897 crate::SegPat::Key("id".into()),
898 ]))
899 .ty(FieldType::Int)
900 .constraint_opt(None::<AlwaysReject>),
901 FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
902 ]);
903 let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
904 assert_eq!(schema.rule_for(&id).unwrap().ty, Some(FieldType::Int));
905 let other = [Seg::Key("meta".into()), Seg::Key("author".into())];
906 assert_eq!(schema.rule_for(&other).unwrap().ty, Some(FieldType::Str));
907 }
908}