pub struct Shape {
pub locations: Vec<Location>,
/* 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)
andshape.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)
andsupershape.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
Fields§
§locations: Vec<Location>
The combination of locations which, combined, produce this shape.
Many cases will only have a single location, but when shapes are simplified, their locations are all retained in the result.
Implementations§
Source§impl Shape
impl Shape
Sourcepub fn accepts(&self, other: &Shape) -> bool
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.
Sourcepub fn accepts_json(&self, json: &Value) -> bool
pub fn accepts_json(&self, json: &Value) -> bool
Returns true iff the given serde_json::Value
satisfies self.
Sourcepub fn accepts_json_bytes(&self, json: &Value) -> bool
pub fn accepts_json_bytes(&self, json: &Value) -> bool
Returns true iff the given [serde_json_bytes::Value
] satisfies self.
Sourcepub fn validate(&self, to_be_validated: &Shape) -> Vec<ShapeMismatch>
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, ...)
.
Sourcepub fn validate_json(&self, json: &Value) -> Vec<ShapeMismatch>
pub fn validate_json(&self, json: &Value) -> Vec<ShapeMismatch>
Shape::validate_json
is to Shape::validate
as Shape::accepts_json
is to Shape::accepts
.
Sourcepub fn validate_json_bytes(&self, json: &Value) -> Vec<ShapeMismatch>
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
.
Sourcepub fn satisfies(&self, other: &Shape) -> bool
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
impl Shape
Sourcepub fn field(
&self,
field_name: &str,
locations: impl IntoIterator<Item = Location>,
) -> Shape
pub fn field( &self, field_name: &str, locations: impl IntoIterator<Item = Location>, ) -> Shape
Returns a new Shape
representing the shape of a given subproperty
(field name) of the self
shape.
Sourcepub fn any_field(&self, locations: impl IntoIterator<Item = Location>) -> Shape
pub fn any_field(&self, locations: impl IntoIterator<Item = Location>) -> Shape
Returns a new Shape
representing the union of all field shapes of
object shapes, or just the shape itself for non-object shapes.
Sourcepub fn item(
&self,
index: usize,
locations: impl IntoIterator<Item = Location>,
) -> Shape
pub fn item( &self, index: usize, locations: impl IntoIterator<Item = Location>, ) -> Shape
Returns a new Shape
representing the shape of a given element of an
array shape.
Sourcepub fn any_item(&self, locations: impl IntoIterator<Item = Location>) -> Shape
pub fn any_item(&self, locations: impl IntoIterator<Item = Location>) -> Shape
Returns a new Shape
representing the union of all element shapes of
array shapes, or just the shape itself for non-array shapes.
Sourcepub fn child(&self, key: Located<NamedShapePathKey>) -> Shape
pub fn child(&self, key: Located<NamedShapePathKey>) -> Shape
Get a child shape, and add the provided locations
to it.
Source§impl Shape
impl Shape
Sourcepub fn from_json(json: &JSON) -> Self
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.
Note that all locations will be empty, because serde_json
doesn’t track locations.
§Panics
If the JSON value can’t be converted into a [serde_json_bytes::Value
]
Sourcepub fn from_json_bytes(json: &JSONBytes) -> Self
pub fn from_json_bytes(json: &JSONBytes) -> Self
Derive a Shape
from a JSON value using the [serde_json_bytes
] crate.
Note that all locations will be empty, because [serde_json_bytes
] doesn’t track locations.
Source§impl Shape
impl Shape
Sourcepub fn case(&self) -> &ShapeCase
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.
Sourcepub fn bool(locations: impl IntoIterator<Item = Location>) -> Self
pub fn bool(locations: impl IntoIterator<Item = Location>) -> Self
Returns a Shape
that accepts any boolean value, true
or false
.
Sourcepub fn bool_value(
value: bool,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn bool_value( value: bool, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a Shape
that accepts only the specified boolean value.
Sourcepub fn string(locations: impl IntoIterator<Item = Location>) -> Self
pub fn string(locations: impl IntoIterator<Item = Location>) -> Self
Returns a Shape
that accepts any string value.
Sourcepub fn string_value(
value: &str,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn string_value( value: &str, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a Shape
that accepts only the specified string value.
Sourcepub fn int(locations: impl IntoIterator<Item = Location>) -> Self
pub fn int(locations: impl IntoIterator<Item = Location>) -> Self
Returns a Shape
that accepts any integer value.
Sourcepub fn int_value(
value: i64,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn int_value( value: i64, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a Shape
that accepts only the specified integer value.
Sourcepub fn float(locations: impl IntoIterator<Item = Location>) -> Self
pub fn float(locations: impl IntoIterator<Item = Location>) -> Self
Returns a Shape
that accepts any floating point value.
Sourcepub fn null(locations: impl IntoIterator<Item = Location>) -> Self
pub fn null(locations: impl IntoIterator<Item = Location>) -> Self
Returns a Shape
that accepts only the JSON null
value.
pub fn is_null(&self) -> bool
Sourcepub fn name(
name: &str,
locations: impl IntoIterator<Item = Location> + Clone,
) -> Self
pub fn name( name: &str, locations: impl IntoIterator<Item = Location> + Clone, ) -> 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.
Sourcepub fn empty_map() -> IndexMap<String, Self>
pub fn empty_map() -> IndexMap<String, Self>
Useful for obtaining the kind of [IndexMap
] this library uses for the
ShapeCase::Object
variant.
Sourcepub fn empty_object(locations: impl IntoIterator<Item = Location>) -> Self
pub fn empty_object(locations: impl IntoIterator<Item = Location>) -> 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
.
Sourcepub fn object(
fields: IndexMap<String, Shape>,
rest: Shape,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn object( fields: IndexMap<String, Shape>, rest: Shape, locations: impl IntoIterator<Item = Location>, ) -> Self
To get a compatible empty mutable [IndexMap
] without directly
depending on the [indexmap
] crate yourself, use Shape::empty_map()
.
Sourcepub fn record(
fields: IndexMap<String, Shape>,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn record( fields: IndexMap<String, Shape>, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a Shape
that accepts any object shape with the given static
fields, with no dynamic fields considered.
Sourcepub fn dict(
value_shape: Shape,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn dict( value_shape: Shape, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a Shape
that accepts any dictionary-like object with dynamic
string properties having a given value shape.
Sourcepub fn array(
prefix: impl IntoIterator<Item = Shape>,
tail: Shape,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn array( prefix: impl IntoIterator<Item = Shape>, tail: Shape, locations: impl IntoIterator<Item = Location>, ) -> Self
Arrays, tuples, and lists are all manifestations of the same underlying
ShapeCase::Array
representation.
Sourcepub fn tuple(
shapes: impl IntoIterator<Item = Shape>,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn tuple( shapes: impl IntoIterator<Item = Shape>, locations: impl IntoIterator<Item = Location>, ) -> Self
A tuple is a ShapeCase::Array
with statically known (though possibly
empty) element shapes and no dynamic tail shape.
Sourcepub fn list(of: Shape, locations: impl IntoIterator<Item = Location>) -> Self
pub fn list(of: Shape, locations: impl IntoIterator<Item = Location>) -> Self
A List<S>
is a ShapeCase::Array
with an empty static prefix
and a
dynamic element shape S
.
Sourcepub fn one(
shapes: impl IntoIterator<Item = Shape>,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn one( shapes: impl IntoIterator<Item = Shape>, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a ShapeCase::One
union of the given shapes, simplified.
Note that locations
in this case should not refer to each individual inner shape, but
to the thing that caused all of these shapes to be combined, like maybe a ->match
. If
there is no obvious cause to point users to, then the location should be empty.
Sourcepub fn all(
shapes: impl IntoIterator<Item = Shape>,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn all( shapes: impl IntoIterator<Item = Shape>, locations: impl IntoIterator<Item = Location>, ) -> Self
Returns a ShapeCase::All
intersection of the given shapes, simplified.
Note that locations
in this case should not refer to each individual inner shape, but
to the thing that caused all of these shapes to be combined, like maybe a IntfA & IntfB
.
If there is no obvious cause to point users to, then the location should be empty.
Sourcepub fn unknown(locations: impl IntoIterator<Item = Location>) -> Self
pub fn unknown(locations: impl IntoIterator<Item = Location>) -> Self
Returns a shape that accepts any JSON value (including ShapeCase::None
and ShapeCase::Unknown
), and is not accepted by any shape other than itself.
pub fn is_unknown(&self) -> bool
Sourcepub fn none() -> Self
pub fn none() -> Self
Returns a shape representing the absence of a JSON value, which is satisfied/accepted only by itself.
Because this represents the absence of a value, it shouldn’t have a location. Basically, nothing can produce none alone, and if it were a union, that union would have its own location.
pub fn is_none(&self) -> bool
Sourcepub fn error(
message: impl Into<String>,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn error( message: impl Into<String>, locations: impl IntoIterator<Item = Location>, ) -> Self
Report a failure of shape processing.
pub fn is_error(&self) -> bool
Sourcepub fn errors(&self) -> impl Iterator<Item = &Error>
pub fn errors(&self) -> impl Iterator<Item = &Error>
Iterate over all errors within this shape, recursively
Sourcepub fn error_with_partial(
message: impl Into<String>,
partial: Shape,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn error_with_partial( message: impl Into<String>, partial: Shape, locations: impl IntoIterator<Item = Location>, ) -> Self
Report a failure of shape processing associated with a partial/best-guess shape that may still be useful.
Sourcepub fn with_locations(
&self,
locations: impl IntoIterator<Item = Location>,
) -> Self
pub fn with_locations( &self, locations: impl IntoIterator<Item = Location>, ) -> Self
Clone the shape, adding the provided locations
to the existing locations.
Trait Implementations§
impl Eq for Shape
impl Send for Shape
impl StructuralPartialEq for Shape
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
§Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling [Attribute
] value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
§Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
[Quirk
] value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the [Condition
] value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);