Skip to main content

TaggedEnumSchema

Struct TaggedEnumSchema 

Source
pub struct TaggedEnumSchema {
    pub tag_field: String,
    pub variants: Vec<(String, ObjectSchema)>,
    pub global_fields: Vec<FieldDef>,
}
Expand description

Schema for a tagged enum (discriminated union)

Used for types with a discriminator field (e.g., tag: “type”, “kind”). Each valid tag value maps to an ObjectSchema describing that variant’s fields. Fields registered globally (via with_enum_array, with_nested_object or with_field_kind) apply to every variant.

§Example (static, closure-based)

use fuzzy_parser::TaggedEnumSchema;

let schema = TaggedEnumSchema::new(
    "type",
    &["AddDerive", "RemoveDerive"],
    |tag| match tag {
        "AddDerive" | "RemoveDerive" => Some(&["target", "derives"][..]),
        _ => None,
    },
)
.with_enum_array("derives", &["Debug", "Clone", "Serialize"])
.with_nested_object("config", &["timeout", "retries"]);

§Example (dynamic, built at runtime)

use fuzzy_parser::{FieldKind, ObjectSchema, TaggedEnumSchema};

// Field names can come from runtime data (config, API spec, ...).
let variant = String::from("AddDerive");
let schema = TaggedEnumSchema::with_tag("type").with_variant(
    variant,
    ObjectSchema::new(["target"])
        .with_field_kind("derives", FieldKind::enum_array(["Debug", "Clone"]))
        .with_field_kind("timeout", FieldKind::Integer),
);

Fields§

§tag_field: String

The discriminator field name (e.g., “type”, “kind”)

§variants: Vec<(String, ObjectSchema)>

The variants: (tag value, schema for that variant’s fields)

§global_fields: Vec<FieldDef>

Fields that apply to every variant (checked after variant fields)

Implementations§

Source§

impl TaggedEnumSchema

Source

pub fn from_json_schema( root: &Value, ) -> Result<SchemaImport<TaggedEnumSchema>, FuzzyError>

Convert a JSON Schema document (e.g. schemars output) into a TaggedEnumSchema.

Expects a oneOf at the root whose branches share a tag property with a const string — the shape produced by #[serde(tag = "type")] (see the module docs for the supported subset).

§Example
use fuzzy_parser::{TaggedEnumSchema, FieldKind};
use serde_json::json;

let json_schema = json!({
    "oneOf": [
        {
            "type": "object",
            "properties": {
                "type": {"type": "string", "const": "AddDerive"},
                "target": {"type": "string"},
                "derives": {"type": "array", "items": {"type": "string", "enum": ["Debug", "Clone"]}}
            },
            "required": ["type", "target"]
        }
    ]
});

let import = TaggedEnumSchema::from_json_schema(&json_schema).unwrap();
assert!(import.schema.is_valid_tag("AddDerive"));
assert!(import.warnings.is_empty());
Source§

impl TaggedEnumSchema

Source

pub fn new<F>( tag_field: impl AsRef<str>, valid_tags: &[&str], fields_for_tag: F, ) -> Self
where F: Fn(&str) -> Option<&'static [&'static str]>,

Create a new tagged enum schema from a field-resolver closure.

The closure is evaluated once per valid tag at construction time, so the schema itself owns its data and carries no generic parameter.

Source

pub fn with_tag(tag_field: impl AsRef<str>) -> Self

Create an empty schema for dynamic construction.

Add variants with with_variant.

Source

pub fn with_variant(self, tag: impl AsRef<str>, schema: ObjectSchema) -> Self

Add (or replace) a variant with its field schema.

Source

pub fn with_enum_array<I, S>( self, field: impl AsRef<str>, valid_values: I, ) -> Self
where I: IntoIterator<Item = S>, S: AsRef<str>,

Add a global enum array field for repair (applies to every variant).

Values in this array field will be fuzzy-matched against valid_values.

§Example
use fuzzy_parser::TaggedEnumSchema;

let schema = TaggedEnumSchema::new("type", &["AddDerive"], |_| Some(&["derives"][..]))
    .with_enum_array("derives", &["Debug", "Clone", "Serialize"]);
// Now "Debg" in derives array will be corrected to "Debug"
Source

pub fn with_nested_object<I, S>( self, field: impl AsRef<str>, valid_fields: I, ) -> Self
where I: IntoIterator<Item = S>, S: AsRef<str>,

Add a global nested object field for repair (applies to every variant).

Field names in this nested object will be fuzzy-matched against valid_fields. For deeper nesting or value shapes inside the nested object, use with_field_kind with FieldKind::Object instead.

§Example
use fuzzy_parser::TaggedEnumSchema;

let schema = TaggedEnumSchema::new("type", &["Configure"], |_| Some(&["config"][..]))
    .with_nested_object("config", &["timeout", "retries", "enabled"]);
// Now "timout" in config object will be corrected to "timeout"
Source

pub fn with_field_kind(self, field: impl AsRef<str>, kind: FieldKind) -> Self

Add (or replace) a global field with an expected value shape.

Global fields apply to every variant, after the variant’s own field kinds.

Source

pub fn is_valid_tag(&self, tag: &str) -> bool

Check if a tag value is valid

Source

pub fn tag_values(&self) -> impl Iterator<Item = &str>

Iterate over the valid tag values.

Source

pub fn variant_schema(&self, tag: &str) -> Option<&ObjectSchema>

Get the field schema for a tag value, if the tag is valid.

Trait Implementations§

Source§

impl Clone for TaggedEnumSchema

Source§

fn clone(&self) -> TaggedEnumSchema

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TaggedEnumSchema

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for TaggedEnumSchema

Source§

fn default() -> TaggedEnumSchema

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.