shape

Struct Shape

Source
pub struct Shape { /* private fields */ }
Expand description

The shape::Shape struct provides a recursive, immutable, reference-counted tree/DAG format for representing and enforcing common structures and usage patterns of JSON-like data.

The Shape system is not bound to any particular programming language, so it does not inherit a data model that it must represent and defend, yet it must adopt/assume some concrete data model, since a type system without a data model to enforce is as useful as a straitjacket on a coat rack. JSON was chosen for its relative simplicity, its ubiquity as a data interchange format used across programming languages, and because JSON is often used in scenarios without a static type system to help catch errors before runtime.

The Shape system has no source syntax for denoting shapes directly, but you can use the Shape::* helper functions to create shapes programmatically, in Rust. Shape::pretty_print() provides a human-readable representation of a Shape for debugging and testing purposes.

All in all, this Static Shape System (SSS) supports the following type-theoretic features:

  • Primitive shapes: Bool, String, Int, Float, Null
  • Singleton primitive shapes: true, false, "hello", 42, null
  • Array shapes, supporting both static tuples and dynamic lists
  • Object shapes, supporting both static fields and dynamic string keys
  • One<S1, S2, ...> union shapes, representing a set of shape alternatives
  • All<S1, S2, ...> intersection shapes, representing a set simultaneous requirements
  • shape.field(name) and shape.item(index) methods for accessing the shape of a subproperty of a shape
  • Name shape references, with support for symbolic subproperty shape access
  • Error shapes, representing a failure of shape processing, with support for chains of errors and partial shape data
  • None shapes, representing the absence of a value (helpful for representing optionality of shapes)
  • subshape.satisfies(supershape) and supershape.accepts(subshape) methods for testing shape relationships
  • shape.accepts_json(json) method for testing whether concrete JSON data satisfies some expected shape
  • shape.pretty_print() method for debugging and testing

Implementations§

Source§

impl Shape

Source

pub fn accepts(&self, other: &Shape) -> bool

Returns true if the other shape meets all the expectations of the self shape. In set theory terms, the set of all values accepted by other is a subset of the set of all values accepted by self.

Source

pub fn accepts_json(&self, json: &Value) -> bool

Returns true iff the given serde_json JSON data satisfies self.

Source

pub fn accepts_json_bytes(&self, json: &Value) -> bool

Returns true iff the given serde_json_bytes JSON data satisfies self.

Source

pub fn validate(&self, to_be_validated: &Shape) -> Vec<ShapeMismatch>

Validates that all expectations of the self shape are met by the to_be_validated shape, erroring with a non-empty vector of ShapeMismatch errors when validation fails.

Note that validate is closer to accepts than satisfies in terms of the direction of the comparison, which is why the implementation uses to_be_validated.satisfies_at_path(self, ...) rather than self.satisfies_at_path(to_be_validated, ...).

Source

pub fn validate_json(&self, json: &Value) -> Vec<ShapeMismatch>

Shape::validate_json is to Shape::validate as Shape::accepts_json is to Shape::accepts.

Source

pub fn validate_json_bytes(&self, json: &Value) -> Vec<ShapeMismatch>

Shape::validate_json_bytes is to Shape::validate as Shape::accepts_json_bytes is to Shape::accepts.

Source

pub fn satisfies(&self, other: &Shape) -> bool

Returns true if the self shape meets all the expectations of the other shape. In set theory terms, self satisfying other means the set of all values accepted by self is a subset of the set of all values accepted by other.

The satisfies method is the inverse of the accepts method, in the sense that a.accepts(b) is equivalent to b.satisfies(a). For historical reasons, the bulk of the accepts/satisfies logic happens in the internal satisfies_at_path method, though I have since realized the accepts direction generalizes a bit better to situations where other is not a Shape, such as Shape::accepts_json(&self, json: &serde_json::Value).

Source§

impl Shape

Source

pub fn field(&self, field_name: &str) -> Shape

Returns a new Shape representing the shape of a given subproperty (field name) of the self shape.

Source

pub fn any_field(&self) -> Shape

Returns a new Shape representing the union of all field shapes of object shapes, or just the shape itself for non-object shapes.

Source

pub fn item(&self, index: usize) -> Shape

Returns a new Shape representing the shape of a given element of an array shape.

Source

pub fn any_item(&self) -> Shape

Returns a new Shape representing the union of all element shapes of array shapes, or just the shape itself for non-array shapes.

Source§

impl Shape

Source

pub fn pretty_print(&self) -> String

Returns a string representation of the Shape.

Please note: this display format does not imply an input syntax or parser for the shape language. To create new Shape elements, use the various Shape::* helper functions.

Source§

impl Shape

Source

pub fn from_json(json: &JSON) -> Self

Derive a Shape from a JSON value, which is almost a lossless conversion except that floating point literals get the general ShapeCase::Float shape, ignoring their particular values.

Source

pub fn from_json_bytes(json: &JSONBytes) -> Self

Derive a Shape from a JSON value using the serde_json_bytes crate.

Source§

impl Shape

Source

pub fn case(&self) -> &ShapeCase

When boolean helper methods like .is_none() and .is_null() are not enough, you can match against the underlying ShapeCase by obtaining an immutable &ShapeCase reference using the shape.case() method.

Source

pub fn bool() -> Self

Returns a Shape that accepts any boolean value, true or false.

Source

pub fn bool_value(value: bool) -> Self

Returns a Shape that accepts only the specified boolean value.

Source

pub fn string() -> Self

Returns a Shape that accepts any string value.

Source

pub fn string_value(value: &str) -> Self

Returns a Shape that accepts only the specified string value.

Source

pub fn int() -> Self

Returns a Shape that accepts any integer value.

Source

pub fn int_value(value: i64) -> Self

Returns a Shape that accepts only the specified integer value.

Source

pub fn float() -> Self

Returns a Shape that accepts any floating point value.

Source

pub fn null() -> Self

Returns a Shape that accepts only the JSON null value.

Source

pub fn is_null(&self) -> bool

Source

pub fn name(name: &str) -> Self

Returns a symbolic reference to a named shape, potentially not yet defined.

In order to add items to the subpath of this named shape, call the .field(name) and/or .item(index) methods.

Note that variable shapes are represented by ShapeCase::Name where the name string includes the initial $ character.

Source

pub fn empty_map() -> IndexMap<String, Self>

Useful for obtaining the kind of IndexMap this library uses for the ShapeCase::Object variant.

Source

pub fn empty_object() -> Self

Returns a Shape that accepts any object shape, regardless of the other shape’s fields or rest shape, because an empty object shape {} imposes no expectations on other objects (except that they are objects).

In the other direction, an empty object shape {} can satisfy itself or any Dict<V> shape (where the Dict may be dynamically empty), but cannot satisfy any object shape with non-empty fields.

Source

pub fn object(fields: IndexMap<String, Shape>, rest: Shape) -> Self

To get a compatible empty mutable [IndexMap] without directly depending on the indexmap crate yourself, use Shape::empty_map().

Source

pub fn record(fields: IndexMap<String, Shape>) -> Self

Returns a Shape that accepts any object shape with the given static fields, with no dynamic fields considered.

Source

pub fn dict(value_shape: Shape) -> Self

Returns a Shape that accepts any dictionary-like object with dynamic string properties having a given value shape.

Source

pub fn array(prefix: &[Shape], tail: Shape) -> Self

Arrays, tuples, and lists are all manifestations of the same underlying ShapeCase::Array representation.

Source

pub fn tuple(shapes: &[Shape]) -> Self

A tuple is a ShapeCase::Array with statically known (though possibly empty) element shapes and no dynamic tail shape.

Source

pub fn list(of: Shape) -> Self

A List<S> is a ShapeCase::Array with an empty static prefix and a dynamic element shape S.

Source

pub fn empty_array() -> Self

Returns a Shape that accepts any empty array, returning Shape::none() for all index accesses.

Source

pub fn one(shapes: &[Shape]) -> Self

Returns a ShapeCase::One union of the given shapes, simplified.

Source

pub fn all(shapes: &[Shape]) -> Self

Returns a ShapeCase::All intersection of the given shapes, simplified.

Source

pub fn none() -> Self

Source

pub fn is_none(&self) -> bool

Source

pub fn error(message: &str) -> Self

Report a failure of shape processing.

Source

pub fn is_error(&self) -> bool

Source

pub fn error_with_range(message: &str, range: OffsetRange) -> Self

Report a failure of shape processing associated with a specific source OffsetRange.

Source

pub fn error_with_partial(message: &str, partial: Shape) -> Self

Report a failure of shape processing associated with a partial/best-guess shape that may still be useful.

Source

pub fn error_with_range_and_partial( message: &str, range: OffsetRange, partial: Shape, ) -> Self

Trait Implementations§

Source§

impl Clone for Shape

Source§

fn clone(&self) -> Shape

Returns a copy 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 Shape

Source§

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

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

impl Display for Shape

Source§

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

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

impl Hash for Shape

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Shape

Source§

fn eq(&self, other: &Shape) -> 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 Eq for Shape

Source§

impl Send for Shape

Source§

impl StructuralPartialEq for Shape

Source§

impl Sync for Shape

Since we’re using std::sync::Arc for reference counting, and Shape is an immutable structure, we can safely implement Send and Sync for Shape.

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, dst: *mut u8)

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

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. 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.