### Resolve media type examples Source: https://docs.rs/oas3/latest/src/oas3/spec/media_type_examples.rs.html Demonstrates resolving examples where single examples are mapped to the 'default' key and non-existent examples return None. ```rust let examples = mt_examples.resolve_all(&spec); // no example with this name defined assert_eq!(examples.get("Go"), None); // single examples are put in "default" key of returned map assert_eq!( examples.get("default").unwrap().value.as_ref().unwrap(), &json!("ferris"), ); ``` -------------------------------- ### Resolve example references Source: https://docs.rs/oas3/latest/src/oas3/spec/media_type_examples.rs.html Shows how to resolve examples that reference components in the OpenAPI specification, including handling of missing references. ```rust #[test] fn resolve_references() { let spec = yaml_serde::from_str::(indoc::indoc! {" openapi: 3.1.0 info: title: Mascots version: 0.0.0 paths: {} components: examples: RustMascot: value: ferris "}) .unwrap(); let mt_examples = MediaTypeExamples::Examples { examples: Map::from([ ( "Rust".to_owned(), ObjectOrReference::Ref { ref_path: "#/components/examples/RustMascot".to_owned(), summary: None, description: None, }, ), ( "Go".to_owned(), ObjectOrReference::Ref { ref_path: "#/components/examples/GoMascot".to_owned(), summary: None, description: None, }, ), ]), }; let examples = mt_examples.resolve_all(&spec); // reference points to non-existent component assert_eq!(examples.get("Go"), None); // reference points to valid example component assert_eq!( examples.get("Rust").unwrap().value.as_ref().unwrap(), &json!("ferris"), ); } ``` -------------------------------- ### MediaType::examples Source: https://docs.rs/oas3/latest/src/oas3/spec/media_type.rs.html Resolves and returns the provided examples for this media type. It takes a reference to the Spec and returns a Map of Example objects. ```APIDOC ## MediaType::examples ### Description Resolves and returns the provided examples for this media type. If no examples are set, returns an empty map. ### Method pub fn examples(&self, spec: &Spec) -> Map ### Parameters - **spec** (&Spec) - Required - The OpenAPI specification to resolve references against. ### Returns - **Map** - A map of example names to resolved Example objects. ``` -------------------------------- ### FromRef implementation for Example Source: https://docs.rs/oas3/latest/src/oas3/spec/example.rs.html Resolves a reference to an Example from the spec's components. Returns Unresolvable error if the reference cannot be found, or MismatchedType if the reference type is not Example. ```rust impl FromRef for Example { fn from_ref(spec: &Spec, path: &str) -> Result { let refpath = path.parse::()?; match refpath.kind { RefType::Example => spec .components .as_ref() .and_then(|cs| cs.examples.get(&refpath.name)) .ok_or_else(|| RefError::Unresolvable(path.to_owned())) .and_then(|oor| oor.resolve(spec)), typ => Err(RefError::MismatchedType(typ, RefType::Example)), } } } ``` -------------------------------- ### Example::as_bytes method Source: https://docs.rs/oas3/latest/src/oas3/spec/example.rs.html Returns the JSON-encoded bytes of the example's value. If value is None, returns an empty vector. ```rust impl Example { /// Returns JSON-encoded bytes of this example's value. pub fn as_bytes(&self) -> Vec { match self.value { Some(ref val) => serde_json::to_string(val).unwrap().as_bytes().to_owned(), None => vec![], } } } ``` -------------------------------- ### MediaTypeExamples implementation Source: https://docs.rs/oas3/latest/src/oas3/spec/media_type_examples.rs.html Default implementation and helper methods for resolving examples and checking if they are empty. ```rust impl Default for MediaTypeExamples { fn default() -> Self { MediaTypeExamples::Examples { examples: Map::new(), } } } impl MediaTypeExamples { /// Returns true if no examples are provided. pub fn is_empty(&self) -> bool { match self { MediaTypeExamples::Example { .. } => false, MediaTypeExamples::Examples { examples } => examples.is_empty(), } } /// Resolves references and returns a map of provided examples keyed by name. /// /// If the `example` field is provided, then the map contains one item, keyed as "default". pub fn resolve_all(&self, spec: &Spec) -> Map { match self { Self::Example { example } => { let example = Example { description: None, summary: None, value: Some(example.clone()), extensions: Map::default(), }; let mut map = Map::new(); map.insert("default".to_owned(), example); map } Self::Examples { examples } => examples .iter() .filter_map(|(name, oor)| { oor.resolve(spec) .map(|obj| (name.clone(), obj)) .map_err(|err| error!("{err}")) .ok() }) .collect(), } } } ``` -------------------------------- ### Parse explicit null example Source: https://docs.rs/oas3/latest/src/oas3/spec/schema.rs.html Verifies that an explicit 'example: null' is parsed as Some(Value::Null), while omitting example yields None. ```rust let spec = indoc::indoc! {" type: [string, 'null'] "}; let schema = yaml_serde::from_str::(spec).unwrap(); assert_eq!(schema.example, None); let spec = indoc::indoc! {" type: [string, 'null'] example: null "}; let schema = yaml_serde::from_str::(spec).unwrap(); assert_eq!(schema.example, Some(serde_json::Value::Null)); ``` -------------------------------- ### Example struct definition with serde attributes Source: https://docs.rs/oas3/latest/src/oas3/spec/example.rs.html Defines the Example struct with optional summary, description, and value fields, plus flattened specification extensions. The value and externalValue fields are mutually exclusive, and only 'x-' prefixed extensions are collected. ```rust use serde::{Deserialize, Serialize}; use super::{spec_extensions, FromRef, Ref, RefError, RefType, Spec}; use crate::Map; /// Multi-purpose example objects. /// /// Will be validated against schema when used in conformance testing. /// /// See . #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] pub struct Example { /// Short description for the example. #[serde(skip_serializing_if = "Option::is_none")] pub summary: Option, /// Long description for the example. /// [CommonMark syntax](https://spec.commonmark.org) MAY be used for rich text representation. #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, // FIXME: Implement (merge with externalValue as enum) /// Embedded literal example. The `value` field and `externalValue` field are mutually /// exclusive. To represent examples of media types that cannot naturally represented /// in JSON or YAML, use a string value to contain the example, escaping where necessary. #[serde(skip_serializing_if = "Option::is_none")] pub value: Option, // // FIXME: Implement (merge with value as enum) // /// A URL that points to the literal example. This provides the capability to reference // /// examples that cannot easily be included in JSON or YAML documents. The `value` field // /// and `externalValue` field are mutually exclusive. // #[serde(skip_serializing_if = "Option::is_none")] // pub externalValue: Option, // /// Specification extensions. /// /// Only "x-" prefixed keys are collected, and the prefix is stripped. /// /// See . #[serde(flatten, with = "spec_extensions")] pub extensions: Map, } ``` -------------------------------- ### MediaTypeExamples tests Source: https://docs.rs/oas3/latest/src/oas3/spec/media_type_examples.rs.html Unit tests for checking empty state, deserialization, serialization, and single example resolution. ```rust #[cfg(all(test, feature = "yaml-spec"))] mod tests { use serde_json::json; use super::*; #[test] fn is_empty() { assert!(MediaTypeExamples::default().is_empty()); assert!(!MediaTypeExamples::Example { example: serde_json::Value::Null } .is_empty()); } #[test] fn deserialize() { assert_eq!( yaml_serde::from_str::(indoc::indoc! {"\n examples: {}\n "}) .unwrap(), MediaTypeExamples::default(), ); assert_eq!( yaml_serde::from_str::(indoc::indoc! {"\n example: null\n "}) .unwrap(), MediaTypeExamples::Example { example: json!(null) }, ); } #[test] fn serialize() { let mt_examples = MediaTypeExamples::default(); assert_eq!( yaml_serde::to_string(&mt_examples).unwrap(), indoc::indoc! {"\n examples: {}\n "}, ); let mt_examples = MediaTypeExamples::Example { example: json!(null), }; assert_eq!( yaml_serde::to_string(&mt_examples).unwrap(), indoc::indoc! {"\n example: null\n "}, ); } #[test] fn single_example() { let spec = yaml_serde::from_str::(indoc::indoc! {"\nopenapi: 3.1.0\ninfo:\n title: Mascots\n version: 0.0.0\npaths: {}\n "}) .unwrap(); let mt_examples = MediaTypeExamples::Example { example: json!("ferris"), }; ``` -------------------------------- ### MediaTypeExamples Enum Definition Source: https://docs.rs/oas3/latest/oas3/spec/enum.MediaTypeExamples.html The structure of the MediaTypeExamples enum, representing either multiple named examples or a single example value. ```rust pub enum MediaTypeExamples { Examples { examples: Map>, }, Example { example: Value, }, } ``` -------------------------------- ### Deserialize and Serialize OpenAPI Extensions Source: https://docs.rs/oas3/latest/src/oas3/spec/spec_extensions.rs.html Functions to deserialize map fields starting with 'x-' and serialize them back with the prefix. ```rust 1use std::fmt; use serde::{de, Deserializer, Serializer}; use crate::Map; /// Deserializes fields of a map beginning with `x-`. pub(crate) fn deserialize<'de, D>( deserializer: D, ) -> Result, D::Error> where D: Deserializer<'de>, { struct ExtraFieldsVisitor; impl<'de> de::Visitor<'de> for ExtraFieldsVisitor { type Value = Map; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("extensions") } fn visit_map(self, mut access: M) -> Result where M: de::MapAccess<'de>, { let mut map = Map::::new(); while let Some((key, value)) = access.next_entry()? { map.insert(key, value); } Ok(map .into_iter() .filter_map(|(key, value)| { key.strip_prefix("x-").map(|key| (key.to_owned(), value)) }) .collect()) } } deserializer.deserialize_map(ExtraFieldsVisitor) } /// Serializes fields of a map prefixed with `x-`. pub(crate) fn serialize( extensions: &Map, serializer: S, ) -> Result where S: Serializer, { serializer.collect_map( extensions .iter() .map(|(key, value)| (format!("x-{key}"), value)), ) } ``` -------------------------------- ### Register HTTP methods using push_method! macro Source: https://docs.rs/oas3/latest/src/oas3/spec/path_item.rs.html This snippet demonstrates the registration of various HTTP methods (PUT, POST, DELETE, OPTIONS, HEAD, PATCH, TRACE) into the methods collection using the push_method! macro. ```rust push_method!(put, PUT); push_method!(post, POST); push_method!(delete, DELETE); push_method!(options, OPTIONS); push_method!(head, HEAD); push_method!(patch, PATCH); push_method!(trace, TRACE); methods } } ``` -------------------------------- ### take Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## take ### Description Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. ### Method take ### Signature fn take(self, n: usize) -> Take where Self: Sized ### Parameters - **n** (usize) - Required - The number of elements to take. ### Return Value Returns a Take iterator that yields the first n elements. ### Notes Available since 1.0.0 (const: unstable). ``` -------------------------------- ### MediaType struct definition Source: https://docs.rs/oas3/latest/oas3/spec/struct.MediaType.html The struct definition for MediaType, showing its fields: schema, examples, encoding, and extensions. ```rust pub struct MediaType { pub schema: Option, pub examples: Option, pub encoding: Map, pub extensions: Map, } ``` -------------------------------- ### Map::new Source: https://docs.rs/oas3/latest/oas3/map/struct.Map.html Creates an empty map. ```APIDOC ## Map::new ### Description Creates an empty map. ### Method new ### Signature pub fn new() -> Self ### Parameters None ### Returns - **Self** - A new empty Map. ``` -------------------------------- ### MapVisitor implementation Source: https://docs.rs/oas3/latest/src/oas3/map.rs.html Implements the MapVisitor for deserialization, providing the logic to populate a Map from a MapAccess. ```rust fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("a map") } fn visit_map(self, mut access: A) -> Result where A: MapAccess<'de>, { let mut map = Map::with_capacity(access.size_hint().unwrap_or(0)); while let Some((key, value)) = access.next_entry()? { map.insert(key, value); } Ok(map) } } deserializer.deserialize_map(MapVisitor { marker: PhantomData, }) } } ``` -------------------------------- ### partition Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Consumes an iterator, creating two collections from it. ```APIDOC ## partition ### Description Consumes an iterator, creating two collections from it. ### Method partition ### Signature fn partition(self, f: F) -> (B, B) where Self: Sized, B: Default + Extend, F: FnMut(&Self::Item) -> bool ### Parameters - **f** (F) - Required - A closure that determines which collection each item goes to. ### Return Value Returns a tuple of two collections. ### Notes Available since 1.0.0 (const: unstable). ``` -------------------------------- ### by_ref Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Creates a by reference adapter for this instance of Iterator. ```APIDOC ## by_ref ### Description Creates a by reference adapter for this instance of Iterator. ### Method by_ref ### Signature fn by_ref(&mut self) -> &mut Self where Self: Sized ### Return Value Returns a mutable reference to the iterator. ### Notes Available since 1.0.0 (const: unstable). ``` -------------------------------- ### fn take(self, n: usize) -> Take Source: https://docs.rs/oas3/latest/oas3/map/struct.Values.html Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Signature fn take(self, n: usize) -> Take where Self: Sized ### Availability 1.0.0 (const: unstable) ``` -------------------------------- ### PathItem methods implementation Source: https://docs.rs/oas3/latest/src/oas3/spec/path_item.rs.html The methods implementation provides an iterator over the operations defined in the PathItem, using a macro to simplify the collection of available HTTP methods. ```rust 95impl PathItem { 96 /// Returns iterator over this path's provided operations, keyed by method. 97 pub fn methods(&self) -> impl IntoIterator { 98 let mut methods = vec![]; 99 100 macro_rules! push_method { 101 ($field:ident, $method:ident) => {{ 102 if let Some(ref op) = self.$field { 103 methods.push((Method::$method, op)) 104 } 105 }}; 106 } 107 108 push_method!(get, GET); ``` -------------------------------- ### Serialize plain reference Source: https://docs.rs/oas3/latest/src/oas3/spec/ref.rs.html Demonstrates that a plain reference without summary or description does not emit null slots during serialization. ```rust // A plain reference should not emit `null` summary/description slots. let reference = ObjectOrReference::<()>::Ref { ref_path: "#/components/examples/RustMascot".to_owned(), summary: None, description: None, }; let serialized = serde_json::to_value(reference).expect("serializing ref"); assert_eq!( serialized, json!({ "$ref": "#/components/examples/RustMascot", }) ); } ``` -------------------------------- ### product Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Iterates over the entire iterator, multiplying all the elements. ```APIDOC ## product ### Description Iterates over the entire iterator, multiplying all the elements. ### Method product ### Signature fn product

(self) -> P where Self: Sized, P: Product ### Returns - **P** - The product of all elements. ``` -------------------------------- ### fn fold(self, init: B, f: F) -> B Source: https://docs.rs/oas3/latest/oas3/map/struct.Iter.html Folds every element into an accumulator by applying an operation, returning the final result. ```APIDOC ## fn fold(self, init: B, f: F) -> B ### Description Folds every element into an accumulator by applying an operation, returning the final result. ### Signature fn fold(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B ### Parameters - **init** (B) - The initial accumulator value. - **f** (F) - A closure that takes the accumulator and an element, returning a new accumulator. ### Returns - **B** - The final accumulator value. ### Stability 1.51.0 (const: unstable) ``` -------------------------------- ### fn by_ref(&mut self) -> &mut Self Source: https://docs.rs/oas3/latest/oas3/map/struct.Values.html Creates a by reference adapter for this instance of Iterator. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Iterator`. ### Signature fn by_ref(&mut self) -> &mut Self where Self: Sized ### Availability 1.0.0 (const: unstable) ``` -------------------------------- ### fn skip(self, n: usize) -> Skip Source: https://docs.rs/oas3/latest/oas3/map/struct.Values.html Creates an iterator that skips the first n elements. ```APIDOC ## fn skip(self, n: usize) -> Skip ### Description Creates an iterator that skips the first `n` elements. ### Signature fn skip(self, n: usize) -> Skip where Self: Sized ### Availability 1.0.0 (const: unstable) ``` -------------------------------- ### Test ObjectSchema YAML Roundtrip Source: https://docs.rs/oas3/latest/src/oas3/spec/schema.rs.html Demonstrates roundtrip serialization and deserialization of an ObjectSchema using YAML. ```rust meta: false name: type: string type: object "}; let original = yaml_serde::from_str::(spec).unwrap(); let serialized = yaml_serde::to_string(&original).unwrap(); pretty_assertions::assert_eq!(spec, serialized); } ``` -------------------------------- ### Map iteration and indexing Source: https://docs.rs/oas3/latest/src/oas3/map.rs.html Implementations for IntoIterator, Index, and IndexMut to allow iteration and key-based access for Map. ```rust impl IntoIterator for Map { type IntoIter = IntoIter; type Item = (K, V); fn into_iter(self) -> Self::IntoIter { IntoIter { inner: self.inner.into_iter(), } } } impl<'a, K, V> IntoIterator for &'a Map { type IntoIter = Iter<'a, K, V>; type Item = (&'a K, &'a V); fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, K, V> IntoIterator for &'a mut Map { type IntoIter = IterMut<'a, K, V>; type Item = (&'a K, &'a mut V); fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl Index<&Q> for Map where K: Borrow + Eq + Hash, Q: Eq + Hash + ?Sized, { type Output = V; fn index(&self, index: &Q) -> &Self::Output { Index::index(&self.inner, index) } } impl IndexMut<&Q> for Map where K: Borrow + Eq + Hash, Q: Eq + Hash + ?Sized, { fn index_mut(&mut self, index: &Q) -> &mut Self::Output { IndexMut::index_mut(&mut self.inner, index) } } ``` -------------------------------- ### Response struct definition Source: https://docs.rs/oas3/latest/src/oas3/spec/response.rs.html Defines the Response struct with serde serialization/deserialization. Fields include description, headers, content, links, and extensions. Headers, content, and links are skipped when empty. Extensions are flattened and only 'x-' prefixed keys are collected. ```rust use serde::{Deserialize, Serialize}; use super::{ spec_extensions, FromRef, Header, Link, MediaType, ObjectOrReference, Ref, RefError, RefType, Spec, }; use crate::Map; /// Describes a single response from an API Operation, including design-time, static `links` /// to operations based on the response. /// /// See . #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] pub struct Response { /// A short description of the response. /// /// [CommonMark syntax](https://spec.commonmark.org) MAY be used for rich text representation. pub description: Option, /// Maps a header name to its definition. /// [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case /// insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL /// be ignored. #[serde(default)] #[serde(skip_serializing_if = "Map::is_empty")] pub headers: Map>, /// A map containing descriptions of potential response payloads. The key is a media type /// or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value /// describes it. For responses that match multiple keys, only the most specific key is /// applicable. e.g. text/plain overrides text/* #[serde(default)] #[serde(skip_serializing_if = "Map::is_empty")] pub content: Map, /// A map of operations links that can be followed from the response. The key of the map /// is a short name for the link, following the naming constraints of the names for /// [Component Objects](https://spec.openapis.org/oas/v3.1.1#components-object). #[serde(default)] #[serde(skip_serializing_if = "Map::is_empty")] pub links: Map>, /// Specification extensions. /// /// Only "x-" prefixed keys are collected, and the prefix is stripped. /// /// See . #[serde(flatten, with = "spec_extensions")] pub extensions: Map, } ``` -------------------------------- ### IntoIter::fmt Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Formats the value using the given formatter. ```APIDOC ## IntoIter::fmt ### Description Formats the value using the given formatter. ### Method fmt ### Signature fn fmt(&self, f: &mut Formatter<'_>) -> Result ### Parameters - **f** (&mut Formatter<'_>) - The formatter to write to. ### Returns - **Result** - The result of the formatting operation. ``` -------------------------------- ### inspect Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Does something with each element of an iterator, passing the value on. ```APIDOC ## inspect ### Description Does something with each element of an iterator, passing the value on. ### Method inspect ### Signature fn inspect(self, f: F) -> Inspect where Self: Sized, F: FnMut(&Self::Item) ### Parameters - **f** (F) - Required - A closure that takes a reference to each item. ### Return Value Returns an Inspect iterator that yields the original items. ### Notes Available since 1.0.0 (const: unstable). ``` -------------------------------- ### Map::with_capacity Source: https://docs.rs/oas3/latest/oas3/map/struct.Map.html Creates an empty map with capacity for at least the specified number of entries. ```APIDOC ## Map::with_capacity ### Description Creates an empty map with capacity for at least `capacity` entries. ### Method with_capacity ### Signature pub fn with_capacity(capacity: usize) -> Self ### Parameters - **capacity** (usize) - Required - The minimum capacity for the map. ### Returns - **Self** - A new empty Map with the specified capacity. ``` -------------------------------- ### Test prefixItems serialization round trip Source: https://docs.rs/oas3/latest/src/oas3/spec/schema.rs.html Serializes a schema with prefixItems containing string and integer schemas and asserts the output matches the original YAML. ```rust let spec = indoc::indoc! {" items: type: boolean prefixItems: - type: string minLength: 5 - type: integer minimum: 0 type: array "}; let original = yaml_serde::from_str::(spec).unwrap(); let serialized = yaml_serde::to_string(&original).unwrap(); pretty_assertions::assert_eq!(spec, serialized); ``` -------------------------------- ### fn scan(self, initial_state: St, f: F) -> Scan Source: https://docs.rs/oas3/latest/oas3/map/struct.Values.html An iterator adapter which, like fold, holds internal state, but unlike fold, produces a new iterator. ```APIDOC ## fn scan(self, initial_state: St, f: F) -> Scan ### Description An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. ### Signature fn scan(self, initial_state: St, f: F) -> Scan where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option ### Availability 1.0.0 (const: unstable) ``` -------------------------------- ### fn partial_cmp_by(self, other: I, partial_cmp: F) -> Option Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Lexicographically compares the elements of this Iterator with those of another using a specified comparison function. This is a nightly-only experimental API. ```APIDOC ## fn partial_cmp_by(self, other: I, partial_cmp: F) -> Option ### Description Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. ### Signature fn partial_cmp_by(self, other: I, partial_cmp: F) -> Option where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, ::Item) -> Option ### Parameters - **other** (I) - Required - An iterator whose elements are compared with this iterator's elements. - **partial_cmp** (F) - Required - A comparison function that takes an element from each iterator and returns an Option. ### Return Value - **Option** - The result of the partial comparison, or None if the elements are not comparable. ``` -------------------------------- ### map_windows Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Calls the given function f for each contiguous window of size N over self and returns an iterator over the outputs of f. ```APIDOC ## map_windows ### Description Calls the given function f for each contiguous window of size N over self and returns an iterator over the outputs of f. ### Method map_windows ### Signature fn map_windows(self, f: F) -> MapWindows where Self: Sized, F: FnMut(&[Self::Item; N]) -> R ### Parameters - **f** (F) - Required - A closure that takes a reference to an array of size N and returns a value. ### Return Value Returns a MapWindows iterator that yields the outputs of f. ### Notes This is a nightly-only experimental API (iter_map_windows). ``` -------------------------------- ### Spec::primary_server Source: https://docs.rs/oas3/latest/oas3/type.OpenApiV3Spec.html Returns a reference to the primary (first) server definition. ```APIDOC ## primary_server ### Description Returns a reference to the primary (first) server definition. ### Method primary_server ### Signature pub fn primary_server(&self) -> Option<&Server> ### Parameters None ### Returns - Option<&Server> - A reference to the primary server if defined, otherwise None. ``` -------------------------------- ### fn inspect(self, f: F) -> Inspect Source: https://docs.rs/oas3/latest/oas3/map/struct.Values.html Does something with each element of an iterator, passing the value on. ```APIDOC ## fn inspect(self, f: F) -> Inspect ### Description Does something with each element of an iterator, passing the value on. ### Signature fn inspect(self, f: F) -> Inspect where Self: Sized, F: FnMut(&Self::Item) ### Availability 1.0.0 (const: unstable) ``` -------------------------------- ### to_yaml Source: https://docs.rs/oas3/latest/src/oas3/lib.rs.html Serializes an OpenAPI spec to a YAML string. Returns a Result with the YAML string or a yaml_serde::Error. ```APIDOC ## to_yaml ### Description Serializes an OpenAPI spec to a YAML string. ### Function Signature pub fn to_yaml(spec: &OpenApiV3Spec) -> Result ### Parameters - **spec** (&OpenApiV3Spec) - Required - The OpenAPI specification to serialize. ### Returns - **Result** - The YAML string representation or an error. ### Feature Flag Requires the `yaml-spec` feature. ``` -------------------------------- ### OpenAPI Reference Implementation in Rust Source: https://docs.rs/oas3/latest/src/oas3/spec/ref.rs.html The core implementation for handling OpenAPI references, including the ObjectOrReference enum, Ref parsing logic, and the FromRef resolution trait. ```rust 1use std::str::FromStr; 2 3use derive_more::derive::{Display, Error}; 4use log::trace; 5use once_cell::sync::Lazy; 6use regex::Regex; 7use serde::{Deserialize, Serialize}; 8 9use super::Spec; 10 11static RE_REF: Lazy = Lazy::new(|| { 12 Regex::new("^(?P[^#]*)#/components/(?P[^/]+)/(?P.+)$").unwrap() 13}); 14 15/// Container for a type of OpenAPI object, or a reference to one. 16#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] 17#[serde(untagged)] 18pub enum ObjectOrReference { 19 /// Object reference. 20 /// 21 /// See . 22 Ref { 23 /// Path, file reference, or URL pointing to object. 24 #[serde(rename = "$ref")] 25 ref_path: String, 26 27 /// Summary override. 28 #[serde(skip_serializing_if = "Option::is_none")] 29 summary: Option, 30 31 /// Description override. 32 #[serde(skip_serializing_if = "Option::is_none")] 33 description: Option, 34 }, 35 36 /// Inline object. 37 Object(T), 38} 39 40impl ObjectOrReference 41where 42 T: FromRef, 43{ 44 /// Resolves the object (if needed) from the given `spec` and returns it. 45 pub fn resolve(&self, spec: &Spec) -> Result { 46 match self { 47 Self::Object(component) => Ok(component.clone()), 48 Self::Ref { ref_path, .. } => T::from_ref(spec, ref_path), 49 } 50 } 51} 52 53/// Object reference error. 54#[derive(Debug, Clone, PartialEq, Display, Error)] 55pub enum RefError { 56 /// Referenced object has unknown type. 57 #[display("Invalid type: {}", _0)] 58 UnknownType(#[error(not(source))] String), 59 60 /// Referenced object was not of expected type. 61 #[display("Mismatched type: cannot reference a {} as a {}", _0, _1)] 62 MismatchedType(RefType, RefType), 63 64 /// Reference path points outside the given spec file. 65 #[display("Unresolvable path: {}", _0)] 66 Unresolvable(#[error(not(source))] String), // TODO: use some kind of path structure 67} 68 69/// Component type of a reference. 70#[derive(Debug, Clone, Copy, PartialEq, Display)] 71pub enum RefType { 72 /// Schema component type. 73 Schema, 74 75 /// Response component type. 76 Response, 77 78 /// Parameter component type. 79 Parameter, 80 81 /// Example component type. 82 Example, 83 84 /// Request body component type. 85 RequestBody, 86 87 /// Header component type. 88 Header, 89 90 /// Security scheme component type. 91 SecurityScheme, 92 93 /// Link component type. 94 Link, 95 96 /// Callback component type. 97 Callback, 98} 99 100impl FromStr for RefType { 101 type Err = RefError; 102 103 fn from_str(typ: &str) -> Result { 104 Ok(match typ { 105 "schemas" => Self::Schema, 106 "responses" => Self::Response, 107 "parameters" => Self::Parameter, 108 "examples" => Self::Example, 109 "requestBodies" => Self::RequestBody, 110 "headers" => Self::Header, 111 "securitySchemes" => Self::SecurityScheme, 112 "links" => Self::Link, 113 "callbacks" => Self::Callback, 114 typ => return Err(RefError::UnknownType(typ.to_owned())), 115 }) 116 } 117} 118 119/// Parsed reference path. 120#[derive(Debug, Clone)] 121pub struct Ref { 122 /// Source file of the object being references. 123 pub source: String, 124 125 /// Type of object being referenced. 126 pub kind: RefType, 127 128 /// Name of object being referenced. 129 pub name: String, 130} 131 132impl FromStr for Ref { 133 type Err = RefError; 134 135 fn from_str(path: &str) -> Result { 136 let parts = RE_REF 137 .captures(path) 138 .ok_or_else(|| RefError::Unresolvable(path.to_owned()))?; 139 140 trace!("creating Ref: {}/{}", &parts["type"], &parts["name"]); 141 142 Ok(Self { 143 source: parts["source"].to_owned(), 144 kind: parts["type"].parse()?, 145 name: parts["name"].to_owned(), 146 }) 147 } 148} 149 150/// Find an object from a reference path (`$ref`). 151/// 152/// Implemented for object types which can be shared via a spec's `components` object. 153pub trait FromRef: Clone { 154 /// Finds an object in `spec` using the given `path`. 155 fn from_ref(spec: &Spec, path: &str) -> Result; 156} 157 158#[cfg(test)] 159mod tests { 160 use assert_matches::assert_matches; 161 use serde_json::json; 162 163 use super::{ObjectOrReference, Ref, RefError}; 164 165 #[test] 166 fn ref_serialization_omits_empty_overrides() { ``` -------------------------------- ### Spec::operation Source: https://docs.rs/oas3/latest/oas3/type.OpenApiV3Spec.html Returns a reference to the operation with the given method and path, or None if not found. ```APIDOC ## operation ### Description Returns a reference to the operation with the given `method` and `path`, or `None` if not found. ### Method operation ### Signature pub fn operation(&self, method: &Method, path: &str) -> Option<&Operation> ### Parameters - **method** (&Method) - Required - The HTTP method of the operation. - **path** (&str) - Required - The path of the operation. ### Returns - Option<&Operation> - A reference to the operation if found, otherwise None. ``` -------------------------------- ### Parse OpenAPI YAML with oas3::from_yaml Source: https://docs.rs/oas3/latest/oas3/index.html Reads an OpenAPI YAML file and parses it using oas3::from_yaml. On success prints the spec, on error prints the error message. ```rust let yaml = std::fs::read_to_string("path/to/openapi.yml").unwrap(); match oas3::from_yaml(yaml) { Ok(spec) => println!("spec: {:?}", spec), Err(err) => println!("error: {}", err) } ``` -------------------------------- ### Test composition keywords support boolean schemas Source: https://docs.rs/oas3/latest/src/oas3/spec/schema.rs.html Parses a schema with allOf, anyOf, and oneOf containing boolean schemas, asserting the correct positions and values. ```rust let spec = indoc::indoc! {" allOf: - type: string - true anyOf: - false - type: number oneOf: - true - $ref: '#/components/schemas/Test' "}; let schema = yaml_serde::from_str::(spec).unwrap(); assert_eq!(2, schema.all_of.len()); assert_matches!( &schema.all_of[1], Schema::Boolean(BooleanSchema(true)), "Second allOf element should be boolean schema with value true", ); assert_eq!(2, schema.any_of.len()); assert_matches!( &schema.any_of[0], Schema::Boolean(BooleanSchema(false)), "First anyOf element should be boolean schema with value false", ); assert_eq!(2, schema.one_of.len()); assert_matches!( &schema.one_of[0], Schema::Boolean(BooleanSchema(true)), "First oneOf element should be boolean schema with value true", ); ``` -------------------------------- ### fn any(&mut self, f: F) -> bool Source: https://docs.rs/oas3/latest/oas3/map/struct.Iter.html Tests if any element of the iterator matches a predicate. ```APIDOC ## fn any(&mut self, f: F) -> bool ### Description Tests if any element of the iterator matches a predicate. ### Signature fn any(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool ### Parameters - **f** (F) - A closure that takes an element and returns a boolean. ### Returns - **bool** - True if any element matches the predicate, false otherwise. ### Stability 1.0.0 (const: unstable) ``` -------------------------------- ### fn min(self) -> Option Source: https://docs.rs/oas3/latest/oas3/map/struct.Iter.html Returns the minimum element of an iterator. ```APIDOC ## fn min(self) -> Option ### Description Returns the minimum element of an iterator. ### Signature fn min(self) -> Option where Self: Sized, Self::Item: Ord ### Returns - **Option** - The minimum element, or None if the iterator is empty. ### Stability 1.0.0 (const: unstable) ``` -------------------------------- ### fn reduce(self, f: F) -> Option Source: https://docs.rs/oas3/latest/oas3/map/struct.Iter.html Reduces the elements to a single one, by repeatedly applying a reducing operation. ```APIDOC ## fn reduce(self, f: F) -> Option ### Description Reduces the elements to a single one, by repeatedly applying a reducing operation. ### Signature fn reduce(self, f: F) -> Option where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item ### Parameters - **f** (F) - A closure that takes two elements and returns a single element. ### Returns - **Option** - The reduced value, or None if the iterator is empty. ### Stability Source§ ``` -------------------------------- ### from_json Source: https://docs.rs/oas3/latest/oas3/fn.from_json.html Deserializes an OpenAPI spec (JSON-format) from a string. ```APIDOC ## from_json ### Description Deserializes an OpenAPI spec (JSON-format) from a string. ### Function Signature pub fn from_json(json: impl AsRef) -> Result ### Parameters - **json** (impl AsRef) - Required - The JSON string to deserialize. ### Returns - **Result** - The deserialized OpenAPI spec or an error. ``` -------------------------------- ### FromRef implementation for Response Source: https://docs.rs/oas3/latest/src/oas3/spec/response.rs.html Implements FromRef for Response to resolve a reference path to a Response object. It parses the path as a Ref, checks that the kind is RefType::Response, and resolves the reference from the components' responses map. Returns RefError::Unresolvable if not found or RefError::MismatchedType if the type is wrong. ```rust impl FromRef for Response { fn from_ref(spec: &Spec, path: &str) -> Result { let refpath = path.parse::()?; match refpath.kind { RefType::Response => spec .components .as_ref() .and_then(|cs| cs.responses.get(&refpath.name)) .ok_or_else(|| RefError::Unresolvable(path.to_owned())) .and_then(|oor| oor.resolve(spec)), typ => Err(RefError::MismatchedType(typ, RefType::Response)), } } } ``` -------------------------------- ### Test prefixItems support boolean schemas Source: https://docs.rs/oas3/latest/src/oas3/spec/schema.rs.html Parses a schema with prefixItems containing true, false, and an inline string schema, asserting the correct types and values. ```rust let spec = indoc::indoc! {" type: array prefixItems: - true - false - type: string "}; let schema = yaml_serde::from_str::(spec).unwrap(); assert_eq!(3, schema.prefix_items.len()); assert_matches!( &schema.prefix_items[0], Schema::Boolean(BooleanSchema(true)), "First prefixItems element should be boolean schema with value true", ); assert_matches!( &schema.prefix_items[1], Schema::Boolean(BooleanSchema(false)), "Second prefixItems element should be boolean schema with value false", ); assert_matches!( &schema.prefix_items[2], Schema::Object(obj) if matches!( obj.as_ref(), ObjectOrReference::Object(ObjectSchema { schema_type: Some(TypeSet::Single(Type::String)), .. }) ), "Third prefixItems element should be inline string schema", ); ``` -------------------------------- ### any Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Tests if any element of the iterator matches a predicate. ```APIDOC ## any ### Description Tests if any element of the iterator matches a predicate. ### Method any ### Signature fn any(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool ### Parameters - **f** (FnMut(Self::Item) -> bool) - Required - The predicate to test each element. ### Returns - **bool** - true if any element matches, false otherwise. ``` -------------------------------- ### fn product

(self) -> P Source: https://docs.rs/oas3/latest/oas3/map/struct.Keys.html Iterates over the entire iterator, multiplying all the elements. This method is available since Rust 1.5.0 and is const unstable. ```APIDOC ## fn product

(self) -> P ### Description Iterates over the entire iterator, multiplying all the elements. ### Method product ### Signature fn product

(self) -> P where Self: Sized, P: Product ### Availability 1.5.0 (const: unstable) ``` -------------------------------- ### fold Source: https://docs.rs/oas3/latest/oas3/map/struct.IntoIter.html Folds every element into an accumulator by applying an operation, returning the final result. ```APIDOC ## fold ### Description Folds every element into an accumulator by applying an operation, returning the final result. ### Method fold ### Signature fn fold(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B ### Parameters - **init** (B) - Required - The initial accumulator value. - **f** (F) - Required - A closure that takes the accumulator and an item, returning the new accumulator. ### Return Value Returns the final accumulator value. ### Notes Available since 1.51.0 (const: unstable). ```