Skip to main content

Schema

Struct Schema 

Source
pub struct Schema { /* private fields */ }
Available on crate feature azure_policy only.
Expand description

A schema represents a type definition that can be used for validation.

Schema is a lightweight wrapper around a [Type] that provides reference counting for efficient sharing and cloning. It serves as the primary interface for working with type definitions in the Regorus type system.

§Usage

Schemas are typically created by deserializing from JSON Schema format:

use serde_json::json;

// Create a schema from JSON
let schema_json = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer", "minimum": 0 }
    },
    "required": ["name"]
});

let schema: Schema = serde_json::from_value(schema_json).unwrap();

§Supported Schema Features

The schema system supports a subset of JSON Schema features needed for Azure Policy and other use cases:

  • Basic types: any, null, boolean, integer, number, string
  • Complex types: array, set, object
  • Value constraints: enum, const
  • Composition: anyOf for union types
  • String constraints: minLength, maxLength, pattern
  • Numeric constraints: minimum, maximum
  • Array constraints: minItems, maxItems
  • Object features: properties, required, additionalProperties
  • Discriminated unions: via allOf with conditional schemas

§Thread Safety

While Schema itself is not Send or Sync due to the use of Rc, it can be safely shared within a single thread and cloned efficiently. For multi-threaded scenarios, consider wrapping in Arc if needed.

§Examples

§Simple String Schema

let schema = json!({ "type": "string", "minLength": 1 });
let parsed: Schema = serde_json::from_value(schema).unwrap();

§Complex Object Schema

let schema = json!({
    "type": "object",
    "properties": {
        "users": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": { "type": "integer" },
                    "email": { "type": "string", "pattern": "^[^@]+@[^@]+$" }
                },
                "required": ["id", "email"]
            }
        }
    }
});
let parsed: Schema = serde_json::from_value(schema).unwrap();

§Union Types with anyOf

let schema = json!({
    "anyOf": [
        { "type": "string" },
        { "type": "integer", "minimum": 0 }
    ]
});
let parsed: Schema = serde_json::from_value(schema).unwrap();

Implementations§

Source§

impl Schema

Source

pub fn as_type(&self) -> &Type

Returns a reference to the underlying type definition.

Source

pub fn from_serde_json_value( schema: Value, ) -> Result<Self, Box<dyn Error + Send + Sync>>

Parse a JSON Schema document into a Schema instance. Provides better error messages than serde_json::from_value.

Source

pub fn from_json_str(s: &str) -> Result<Self, Box<dyn Error + Send + Sync>>

Parse a JSON Schema document from a string into a Schema instance. Provides better error messages than serde_json::from_str.

Source

pub fn validate(&self, value: &Value) -> Result<(), ValidationError>

Validates a Value against this schema.

Returns Ok(()) if the value conforms to the schema, or a ValidationError with detailed error information if validation fails.

§Example
use regorus::schema::Schema;
use regorus::Value;
use serde_json::json;

let schema_json = json!({
    "type": "string",
    "minLength": 1,
    "maxLength": 10
});
let schema = Schema::from_serde_json_value(schema_json).unwrap();
let value = Value::from("hello");

assert!(schema.validate(&value).is_ok());

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<'de> Deserialize<'de> for Schema

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserializes a JSON Schema into a Schema instance.

This method handles the deserialization of JSON Schema documents into Regorus’ internal type system. It supports two main formats:

  1. Regular typed schemas - Standard JSON Schema with a type field
  2. Union schemas - Schemas using anyOf to represent union types
§Supported JSON Schema Formats
§Regular Type Schemas

Standard JSON Schema documents with a type field are deserialized directly:

{
  "type": "string",
  "minLength": 1,
  "maxLength": 100
}
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["name"]
}
§Union Type Schemas with anyOf

Schemas using anyOf are converted to Type::AnyOf variants:

{
  "anyOf": [
    { "type": "string" },
    { "type": "integer", "minimum": 0 },
    { "type": "null" }
  ]
}
§Error Handling

This method will return a deserialization error if:

  • The JSON contains unknown/unsupported fields (due to deny_unknown_fields)
  • The JSON structure doesn’t match any supported schema format
  • Individual type definitions within the schema are invalid
  • Required fields are missing (e.g., type field for regular schemas)

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> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,