Skip to main content

Event

Enum Event 

Source
#[non_exhaustive]
pub enum Event<'input> {
Show 13 variants
#[non_exhaustive]
StreamStart,
#[non_exhaustive]
StreamEnd,
#[non_exhaustive]
DocumentStart { explicit: bool, version: Option<YamlVersion>, },
#[non_exhaustive]
DocumentEnd { explicit: bool, },
#[non_exhaustive]
Alias { anchor_id: usize, },
#[non_exhaustive]
Anchor { anchor_id: usize, name: Cow<'input, str>, },
#[non_exhaustive]
UnresolvedAlias { name: Cow<'input, str>, },
#[non_exhaustive]
Comment { value: Cow<'input, str>, placement: Placement, },
#[non_exhaustive]
Scalar { value: Cow<'input, str>, style: ScalarStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, },
#[non_exhaustive]
SequenceStart { style: StructureStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, },
#[non_exhaustive]
SequenceEnd,
#[non_exhaustive]
MappingStart { style: StructureStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, },
#[non_exhaustive]
MappingEnd,
}
Expand description

An event generated by the YAML parser.

Events are used in the low-level event-based API (push parser). The API entrypoint is the EventReceiver trait.

Inspect events with matches!, if let, or match, using { .. } for every variant, including those that currently have no fields. Ignoring unneeded fields allows future metadata to be added without breaking these patterns. A complete match needs a fallback arm because new event variants may also be added.

Normal builds provide no whole-event equality. Classify an event by its variant, then inspect only the fields you need. The opt-in test_equality feature enables equality for tests, comparing the event variant and its core fields. It ignores scalar implicitness and extended_details metadata (block-header syntax and document-end explicitness). Source information may be unavailable on synthetic events; enabling optional capture (including through another dependency) must not change equality. Compare those fields explicitly when testing source syntax. Existing document-start explicitness and version are compared.

Constructors support synthetic events, ParserTrait implementations, and crate::ReplayParser streams. To retain an existing event beyond its source’s lifetime, use Self::into_owned, which preserves all metadata. Self::as_borrowed provides a view without cloning owned payloads. Construction does not enable equality in normal builds.

use granit_parser::{Event, Parser};
let (event, _) = Parser::new_from_str("hello").nth(2).unwrap().unwrap();
assert!(matches!(event, Event::Scalar { .. }));
if let Event::Scalar { value, .. } = event {
    assert_eq!(value, "hello");
}

Whole-event equality is intentionally unavailable by default:

ⓘ
use granit_parser::Event;
fn equal_events(left: Event<'_>, right: Event<'_>) -> bool {
    left == right
}

Direct struct-literal construction outside this crate is not supported:

ⓘ
use granit_parser::Event;
let event = Event::Alias { anchor_id: 1 };

Use constructors to rebuild an event or provide synthetic parser input:

use granit_parser::{Event, Marker, ParserTrait, ReplayParser, ScalarStyle, Span};
let event = Event::new_scalar("generated".into(), ScalarStyle::plain(), 0, None);
let span = Span::empty(Marker::new(0, 1, 0));
let mut replay = ReplayParser::new(vec![(event, span)], 0);
let (event, _) = replay.next_event().unwrap().unwrap();
assert!(matches!(event, Event::Scalar { value, .. } if value == "generated"));

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

#[non_exhaustive]
StreamStart

Event generated at the very beginning of parsing.

§

#[non_exhaustive]
StreamEnd

Last event that will be generated by the parser. Signals EOF.

§

#[non_exhaustive]
DocumentStart

The start of a YAML document.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§explicit: bool

Whether this is an explicit document start marker (---).

When false, the document start is implicit.

§version: Option<YamlVersion>

YAML version declared by a preceding %YAML directive, if any.

§

#[non_exhaustive]
DocumentEnd

The end of a YAML document.

This event is emitted for both explicit document end markers (...) and implicit document ends. The extended_details feature exposes whether the marker was written.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§explicit: bool

Whether the source contains an explicit ... end marker.

§

#[non_exhaustive]
Alias

A resolved YAML alias.

The companion Span covers the complete *name token, preserving the original name through its source range. With Options::emit_anchor_events, Self::Anchor connects the target ID to its definition’s name and source range.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§anchor_id: usize

The anchor ID the alias refers to.

§

#[non_exhaustive]
Anchor

Metadata for an anchor definition on the immediately preceding node in its parser’s stream.

Emitted only when Options::emit_anchor_events is true, immediately after the anchored Self::Scalar, Self::SequenceStart, or Self::MappingStart, before any collection children. This is presentation metadata, not an additional YAML node. The companion Span covers the complete &name token, whose source position precedes the node content. Comments between properties and content can precede the node event. Emitting the node first ensures that a failure before its event is emitted cannot leave anchor metadata without an associated node event, even during document recovery.

This adjacency guarantee applies to an individual Parser. See crate::ParserStack for ordering when sources are interleaved.

Repeated names receive distinct IDs; aliases refer to the most recent preceding definition in the same document. IDs match those on node and Self::Alias events, including when Parser::set_anchor_offset is used.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§anchor_id: usize

The assigned internal anchor ID.

§name: Cow<'input, str>

The original anchor name, without the leading &.

§

#[non_exhaustive]
UnresolvedAlias

An alias without a preceding anchor definition in its document.

Emitted only when Options::emit_unresolved_aliases is true. The companion Span covers the complete alias token, including *. This event occupies a node position but represents an invalid reference; a later anchor definition does not resolve it retroactively.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§name: Cow<'input, str>

The original alias name, without the leading *.

§

#[non_exhaustive]
Comment

A YAML source comment.

Comments are presentation metadata, not YAML data nodes. The payload is the raw text exactly after #, excluding only the line break. The placement is a best-effort hint for correlating the comment with nearby YAML presentation. The companion parser Span covers the whole source comment, including # and excluding the line break.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§value: Cow<'input, str>

Raw comment payload exactly after #, excluding only the line break.

§placement: Placement

Best-effort placement relative to nearby YAML content.

§

#[non_exhaustive]
Scalar

A YAML scalar value.

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§value: Cow<'input, str>

The scalar value after YAML escape processing.

§style: ScalarStyle

The source notation used for the scalar.

§anchor_id: usize

The anchor ID defined on this scalar, or 0 if it has no anchor.

§tag: Option<Cow<'input, Tag>>

The resolved tag attached to this scalar, if any.

§

#[non_exhaustive]
SequenceStart

The start of a YAML sequence (array).

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§style: StructureStyle

The notation style used for the sequence.

§anchor_id: usize

The anchor ID defined on this sequence, or 0 if it has no anchor.

§tag: Option<Cow<'input, Tag>>

The resolved tag attached to this sequence, if any.

§

#[non_exhaustive]
SequenceEnd

The end of a YAML sequence (array).

§

#[non_exhaustive]
MappingStart

The start of a YAML mapping (object, hash).

Fields

This variant is marked as non-exhaustive
Non-exhaustive enum variants could have additional fields added in future. Therefore, non-exhaustive enum variants cannot be constructed in external crates and cannot be matched against.
§style: StructureStyle

The notation style used for the mapping (Flow or Block).

§anchor_id: usize

The anchor ID defined on this mapping, or 0 if it has no anchor.

§tag: Option<Cow<'input, Tag>>

The resolved tag attached to this mapping, if any.

§

#[non_exhaustive]
MappingEnd

The end of a YAML mapping (object, hash).

Implementations§

Source§

impl<'input> Event<'input>

Source

pub fn into_owned(self) -> Event<'static>

Retain this event independently of its source, preserving every field.

Owned strings and tags are moved without cloning. Borrowed payloads are copied into owned storage. All source metadata is retained, including optional extended details.

use granit_parser::{Event, Parser};
let events: Vec<Event<'static>> = {
    let input = String::from("message: hello");
    Parser::new_from_str(&input)
        .map(|result| result.unwrap().0.into_owned())
        .collect()
};
assert!(events.iter().any(|event| event.scalar().is_some()));
Source

pub fn as_borrowed(&self) -> Event<'_>

Borrow this event’s payloads without allocating, preserving every field.

The returned event borrows from self, even when its payloads are owned. Use Self::into_owned on the result if it must outlive this borrow.

use granit_parser::{Event, ScalarStyle};
let event = Event::new_scalar(String::from("hello").into(), ScalarStyle::plain(), 0, None);
let borrowed = event.as_borrowed();
assert_eq!(borrowed.scalar().unwrap().0, "hello");
Source

pub const fn stream_start() -> Self

Create a stream-start event.

Source

pub const fn stream_end() -> Self

Create a stream-end event.

Source

pub const fn sequence_end() -> Self

Create a sequence-end event.

Source

pub const fn mapping_end() -> Self

Create a mapping-end event.

Source

pub const fn document_start( explicit: bool, version: Option<YamlVersion>, ) -> Self

Create a document-start event with its explicit-marker flag and declared YAML version.

Source

pub const fn document_end() -> Self

Create a document-end event with no written end marker.

This constructor takes no parameters in every feature configuration. With extended_details, use with_explicit_end to describe a written ... marker.

Source

pub fn with_explicit_end(self, explicit: bool) -> Self

Set whether a document-end event has a written ... marker.

Returns this event with the supplied flag. Events other than Self::DocumentEnd are returned unchanged.

Source

pub const fn alias(anchor_id: usize) -> Self

Create a resolved alias referring to anchor_id.

Source

pub fn anchor(anchor_id: usize, name: Cow<'input, str>) -> Self

Create anchor metadata with the assigned ID and original name (without &).

Source

pub fn unresolved_alias(name: Cow<'input, str>) -> Self

Create an unresolved alias with its original name (without *).

Source

pub fn comment(value: Cow<'input, str>, placement: Placement) -> Self

Create a comment with its raw text (without #) and placement hint.

Source

pub fn new_scalar( value: Cow<'input, str>, style: ScalarStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, ) -> Self

Create a scalar event.

§Parameters
  • value: decoded scalar content.
  • style: source notation and its syntax metadata.
  • anchor_id: anchor defined on this node, or zero for none.
  • tag: resolved explicit tag, if present.
§Returns

A scalar event containing the supplied value and properties.

Source

pub fn sequence_start( style: StructureStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, ) -> Self

Create a sequence-start event.

§Parameters
  • style: block or flow notation.
  • anchor_id: anchor defined on this node, or zero for none.
  • tag: resolved explicit tag, if present.
§Returns

A sequence-start event containing the supplied properties.

Source

pub fn mapping_start( style: StructureStyle, anchor_id: usize, tag: Option<Cow<'input, Tag>>, ) -> Self

Create a mapping-start event.

§Parameters
  • style: block or flow notation.
  • anchor_id: anchor defined on this node, or zero for none.
  • tag: resolved explicit tag, if present.
§Returns

A mapping-start event containing the supplied properties.

Source

pub fn anchor_id(&self) -> Option<usize>

Return the anchor ID defined by this event, if any.

Returns Some(id) when this event defines an anchor on a scalar, sequence, or mapping node, or describes that definition with Self::Anchor. The reserved ID 0 returns None. Returns None for all other events, including resolved and unresolved aliases (which reference anchors rather than defining them; use Self::alias_id to obtain a resolved target anchor ID). To count anchored nodes once, also require Self::is_node, since Self::Anchor repeats the node’s ID.

Source

pub fn alias_id(&self) -> Option<usize>

Return the target anchor ID if this event is a resolved alias.

Returns None for unresolved aliases and non-alias events. Use Self::is_alias to recognize either kind of alias, or match Self::UnresolvedAlias to obtain its name.

Source

pub fn is_alias(&self) -> bool

Return whether this event is a resolved or unresolved alias.

Source

pub fn tag(&self) -> Option<&Tag>

Return the resolved tag carried by this node event, if any.

Source

pub fn scalar(&self) -> Option<(&str, ScalarStyle)>

Return the scalar value and style, if this event is a scalar.

Source

pub fn is_node(&self) -> bool

Return whether this event represents a YAML node (value).

Returns true for scalars, collection starts, and resolved or unresolved aliases, all of which occupy a node position. Returns false for structural events such as StreamStart, DocumentStart, collection ends, and presentation metadata such as Self::Anchor.

Trait Implementations§

Source§

impl<'input> Clone for Event<'input>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<'input> Debug for Event<'input>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'input> Forget for Event<'input>

§

impl<'input> Freeze for Event<'input>

§

impl<'input> Move for Event<'input>

§

impl<'input> RefUnwindSafe for Event<'input>

§

impl<'input> Send for Event<'input>

§

impl<'input> Sync for Event<'input>

§

impl<'input> Unpin for Event<'input>

§

impl<'input> UnsafeUnpin for Event<'input>

§

impl<'input> UnwindSafe for Event<'input>

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 = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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.