Enum Schema

Source
pub enum Schema {
    Empty {
        definitions: Definitions,
        metadata: Metadata,
    },
    Ref {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        ref_: String,
    },
    Type {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        type_: Type,
    },
    Enum {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        enum_: BTreeSet<String>,
    },
    Elements {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        elements: Box<Schema>,
    },
    Properties {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        properties: BTreeMap<String, Schema>,
        optional_properties: BTreeMap<String, Schema>,
        properties_is_present: bool,
        additional_properties: bool,
    },
    Values {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        values: Box<Schema>,
    },
    Discriminator {
        definitions: Definitions,
        metadata: Metadata,
        nullable: bool,
        discriminator: String,
        mapping: BTreeMap<String, Schema>,
    },
}
Expand description

A pattern-matching-friendly representation of a JSON Typedef schema.

Each variant of this schema corresponds to one of the eight “forms” a schema may take on. All of the forms share the following fields:

  • definitions corresponds to the JSON Typedef keyword of the same name. This should only be non-empty on root schemas. Otherwise, Schema::validate will return SchemaValidateError::NonRootDefinitions.

  • metadata corresponds to the JSON Typedef keyword of the same name. Use this to convey information not pertinent to validation, such as hints for code generation. Do not expect other parties to understand the fields inside metadata unless you’ve agreed upon them out-of-band.

Except for Schema::Empty, all of the forms also share one additional field:

  • nullable corresponds to the JSON Typedef keyword of the same name. If set to “true”, then regardless of any other considerations the schema will accept JSON null as valid.

Schema::Empty omits nullable because it’s redundant; schemas of the empty form already accept null anyway.

For convenience, these three common properties have associated borrowing “getters”: Schema::definitions, Schema::metadata, and Schema::nullable.

If you are trying to parse a JSON Typedef schema from JSON, see SerdeSchema and Schema::from_serde_schema.

use jtd::{SerdeSchema, Schema};
use serde_json::json;

assert_eq!(
    Schema::from_serde_schema(serde_json::from_value(json!({
        "elements": {
            "type": "uint32",
            "nullable": true
        }
    })).unwrap()).unwrap(),
    jtd::Schema::Elements {
        definitions: Default::default(),
        metadata: Default::default(),
        nullable: false,
        elements: Box::new(jtd::Schema::Type {
            definitions: Default::default(),
            metadata: Default::default(),
            nullable: true,
            type_: jtd::Type::Uint32,
        })
    }
);

Variants§

§

Empty

The empty form.

The empty form will accept all inputs. It corresponds to the “top” type of many programming language, like Java’s Object or TypeScript’s any.

Fields

§definitions: Definitions
§metadata: Metadata
§

Ref

The ref form.

The ref form accepts whatever the definition it refers to accepts.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§ref_: String

The name of the definition being referred to.

§

Type

The type form.

The type form accepts JSON “primitives” (booleans, numbers, strings) whose value fall within a certain “type”. These types are enumerated in Type.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§type_: Type

The type of primitive value accepted.

§

Enum

The enum form.

The enum form accepts JSON strings whose values are within an enumerated set.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§enum_: BTreeSet<String>

The values the schema accepts.

§

Elements

The elements form.

The elements form accepts JSON arrays, and each element of the array is validated against a sub-schema.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§elements: Box<Schema>

A schema for the elements of the array.

§

Properties

The properties form.

The properties form accepts JSON objects being used as “structs”.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§properties: BTreeMap<String, Schema>

The required properties of the “struct”, and the schema that each must satisfy.

§optional_properties: BTreeMap<String, Schema>

The optional properties of the “struct”, and the schema that each must satisfy if present.

§properties_is_present: bool

Whether the properties keyword is present on the schema.

It is invalid to set this to false while having properties be non-empty.

This is used only to handle the corner case of a properties-form schema being used to validate a non-object; in order to ensure the returned schema_path points to a part of the schema that really exists, validators need to be able to tell the difference between properties being an empty object versus being omitted from the schema.

This field does not affect whether an input is valid. It only affects the schema_path that will be returned if that input is not an object. For more details, see the first sub-bullet after “Otherwise” in RFC 8927, Section 3.3.6.

Schema::from_serde_schema correctly handles populating this field. If you are constructing schemas by hand and want to play it safe, it is always safe to set this to true.

§additional_properties: bool

Whether additional properties not specified in properties or optional_properties are permitted.

§

Values

The values form.

The values form accepts JSON objects being used as “dictionaries”; each value of the dictionary is validated against a sub-schema.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§values: Box<Schema>

A schema for the values of the “dictionary” object.

§

Discriminator

The discriminator form.

The discriminator form accepts JSON objects being used as “discriminated unions”, or “tagged unions”.

Fields

§definitions: Definitions
§metadata: Metadata
§nullable: bool
§discriminator: String

The “discriminator” property of the schema.

For an input to be valid, this property must exist and its value must be a key in mapping.

§mapping: BTreeMap<String, Schema>

A mapping from the value of the discriminator property in the input to a schema that the rest of the input (without the discriminator property) must satisfy.

Implementations§

Source§

impl Schema

Source

pub fn into_serde_schema(self) -> SerdeSchema

Converts a Schema into a SerdeSchema.

use jtd::{Schema, SerdeSchema, Type};

assert_eq!(
    SerdeSchema {
        type_: Some("uint8".to_owned()),
        ..Default::default()
    },
    Schema::Type {
        definitions: Default::default(),
        metadata: Default::default(),
        nullable: false,
        type_: Type::Uint8,
    }.into_serde_schema(),
);
Source

pub fn from_serde_schema( serde_schema: SerdeSchema, ) -> Result<Self, FromSerdeSchemaError>

Constructs a Schema from a SerdeSchema.

use jtd::{Schema, SerdeSchema, Type};

assert_eq!(
    Schema::Type {
        definitions: Default::default(),
        metadata: Default::default(),
        nullable: false,
        type_: Type::Uint8,
    },
    Schema::from_serde_schema(SerdeSchema {
        type_: Some("uint8".to_owned()),
        ..Default::default()
    }).unwrap(),
);

See the documentation for FromSerdeSchemaError for examples of how this function may return an error.

Source

pub fn validate(&self) -> Result<(), SchemaValidateError>

Ensures a Schema is well-formed.

use jtd::{Schema, Type};

let schema = Schema::Type {
    definitions: Default::default(),
    metadata: Default::default(),
    nullable: false,
    type_: Type::Uint8,
};

schema.validate().expect("Invalid schema");

See the documentation for SchemaValidateError for examples of how this function may return an error.

Source

pub fn definitions(&self) -> &BTreeMap<String, Schema>

Gets the schema’s definitions.

use jtd::{Definitions, Schema};

assert_eq!(
    &vec![(
        "foo".to_owned(),
        Schema::Empty {
            definitions: Default::default(),
            metadata: Default::default(),
        },
    )].into_iter().collect::<Definitions>(),

     Schema::Empty {
         definitions: vec![(
            "foo".to_owned(),
            Schema::Empty {
                definitions: Default::default(),
                metadata: Default::default(),
            },
        )].into_iter().collect(),
         metadata: Default::default(),
     }.definitions(),
);
Source

pub fn metadata(&self) -> &BTreeMap<String, Value>

Gets the schema’s metadata.

use jtd::{Metadata, Schema};
use serde_json::json;

assert_eq!(
    &vec![(
        "foo".to_owned(),
        json!("bar"),
    )].into_iter().collect::<Metadata>(),

    Schema::Empty {
        definitions: Default::default(),
        metadata: vec![(
           "foo".to_owned(),
           json!("bar"),
       )].into_iter().collect(),
    }.metadata(),
);
Source

pub fn nullable(&self) -> bool

Gets whether the schema is nullable.

For Schema::Empty, this always returns true. For all other forms, this fetches the nullable property.

use jtd::{Schema, Type};

assert!(
    Schema::Empty {
        definitions: Default::default(),
        metadata: Default::default(),
    }.nullable(),
);

assert!(
    !Schema::Type {
        definitions: Default::default(),
        metadata: Default::default(),
        nullable: false,
        type_: Type::Uint8,
    }.nullable(),
);

Trait Implementations§

Source§

impl Clone for Schema

Source§

fn clone(&self) -> Schema

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Schema

Source§

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

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

impl PartialEq for Schema

Source§

fn eq(&self, other: &Schema) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Schema

Auto Trait Implementations§

§

impl Freeze for Schema

§

impl RefUnwindSafe for Schema

§

impl Send for Schema

§

impl Sync for Schema

§

impl Unpin for Schema

§

impl UnwindSafe for Schema

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.