Struct Script

Source
pub struct Script<'a> { /* private fields */ }
Expand description

Main ASS script container with zero-copy lifetime-generic design

Uses &'a str spans throughout the AST to avoid allocations during parsing. Thread-safe via immutable design after construction.

Implementations§

Source§

impl<'a> Script<'a>

Source

pub fn parse(source: &'a str) -> Result<Self>

Parse ASS script from source text with zero-copy design

Performs full validation and partial error recovery. Returns script even with errors - check issues() for problems.

§Performance

Target <5ms for 1KB typical scripts. Uses minimal allocations via zero-copy spans referencing input text.

§Example
let script = Script::parse("[Script Info]\nTitle: Test")?;
assert_eq!(script.version(), ass_core::ScriptVersion::AssV4);
§Errors

Returns an error if the source contains malformed section headers or other unrecoverable syntax errors.

Source

pub const fn builder() -> ScriptBuilder<'a>

Create a new script builder for parsing with optional extensions

The builder pattern allows configuration of parsing options including extension registry for custom tag handlers and section processors.

§Example
let registry = ExtensionRegistry::new();
let script = Script::builder()
    .with_registry(&registry)
    .parse("[Script Info]\nTitle: Test")?;
let script = Script::builder()
    .parse("[Script Info]\nTitle: Test")?;
Source

pub fn parse_partial( &self, range: Range<usize>, new_text: &str, ) -> Result<ScriptDeltaOwned>

Parse incrementally with range-based updates for editors

Updates only the specified range, keeping other sections unchanged. Enables <2ms edit responsiveness for interactive editing.

§Arguments
  • range - Byte range in source to re-parse
  • new_text - Replacement text for the range
§Returns

Delta containing changes that can be applied to existing script.

§Errors

Returns an error if the new text contains malformed section headers or other unrecoverable syntax errors in the specified range.

Source

pub const fn version(&self) -> ScriptVersion

Get script version detected during parsing

Source

pub fn sections(&self) -> &[Section<'a>]

Get all parsed sections in document order

Source

pub fn issues(&self) -> &[ParseIssue]

Get parse issues (warnings, recoverable errors)

Source

pub const fn source(&self) -> &'a str

Get source text that spans reference

Source

pub fn styles_format(&self) -> Option<&[&'a str]>

Get format fields for [V4+ Styles] section

Source

pub fn events_format(&self) -> Option<&[&'a str]>

Get format fields for [Events\] section

Source

pub fn parse_style_line_with_context( &self, line: &'a str, line_number: u32, ) -> Result<Style<'a>, ParseError>

Parse a style line with context from the script

Uses the script’s stored format for [V4+ Styles] section if available, otherwise falls back to default format.

§Arguments
  • line - The style line to parse (without “Style:” prefix)
  • line_number - The line number for error reporting
§Returns

Parsed Style or error if the line is malformed

§Errors

Returns ParseError::InsufficientFields if the line has fewer fields than expected

Source

pub fn parse_event_line_with_context( &self, line: &'a str, line_number: u32, ) -> Result<Event<'a>, ParseError>

Parse an event line with context from the script

Uses the script’s stored format for [Events\] section if available, otherwise falls back to default format.

§Arguments
  • line - The event line to parse (e.g., “Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Text”)
  • line_number - The line number for error reporting
§Returns

Parsed Event or error if the line is malformed

§Errors

Returns ParseError::InvalidEventType if the line doesn’t start with a valid event type Returns ParseError::InsufficientFields if the line has fewer fields than expected

Source

pub fn parse_line_auto( &self, line: &'a str, line_number: u32, ) -> Result<(SectionType, LineContent<'a>), ParseError>

Parse a line based on its section context

Automatically determines the section type from the line content and parses accordingly.

§Arguments
  • line - The line to parse
  • line_number - The line number for error reporting
§Returns

A tuple of (section_type, parsed_content) or error

§Errors

Returns error if the line format is invalid or section type cannot be determined

Source

pub fn find_section(&self, section_type: SectionType) -> Option<&Section<'a>>

Find section by type

Source

pub fn validate_spans(&self) -> bool

Validate all spans reference source text correctly

Debug helper to ensure zero-copy invariants are maintained.

Source

pub fn section_range(&self, section_type: SectionType) -> Option<Range<usize>>

Get byte range for a section

Returns the byte range (start..end) for the specified section type, or None if the section doesn’t exist or has no span.

Source

pub fn section_at_offset(&self, offset: usize) -> Option<&Section<'a>>

Find section containing the given byte offset

Returns the section that contains the specified byte offset, or None if no section contains that offset.

Source

pub fn section_boundaries(&self) -> Vec<(SectionType, Range<usize>)>

Get all section boundaries for quick lookup

Returns a vector of (SectionType, Range) pairs for all sections that have valid spans. Useful for building lookup tables or determining which sections need reparsing after edits.

Source

pub fn update_line_at_offset( &mut self, offset: usize, new_line: &'a str, line_number: u32, ) -> Result<LineContent<'a>, ParseError>

Update a line in the script at the given byte offset

Finds the section containing the offset and updates the appropriate line. Returns the old line content if successful.

§Arguments
  • offset - Byte offset of the line to update
  • new_line - New line content
  • line_number - Line number for error reporting
§Returns

The old line content if successful, or error if update failed

§Errors

Returns error if offset is invalid or line cannot be parsed

Source

pub fn add_section(&mut self, section: Section<'a>) -> usize

Add a new section to the script

§Arguments
  • section - The section to add
§Returns

The index of the added section

Source

pub fn remove_section( &mut self, index: usize, ) -> Result<Section<'a>, ParseError>

Remove a section by index

§Arguments
  • index - The index of the section to remove
§Returns

The removed section if successful

§Errors

Returns error if index is out of bounds

Source

pub fn add_style(&mut self, style: Style<'a>) -> usize

Add a style to the [V4+ Styles] section

Creates the section if it doesn’t exist.

§Arguments
  • style - The style to add
§Returns

The index of the style within the styles section

Source

pub fn add_event(&mut self, event: Event<'a>) -> usize

Add an event to the [Events\] section

Creates the section if it doesn’t exist.

§Arguments
  • event - The event to add
§Returns

The index of the event within the events section

Source

pub fn set_styles_format(&mut self, format: Vec<&'a str>)

Update format for styles section

Source

pub fn set_events_format(&mut self, format: Vec<&'a str>)

Update format for events section

Source

pub fn batch_update_lines( &mut self, operations: Vec<UpdateOperation<'a>>, ) -> BatchUpdateResult<'a>

Perform multiple line updates in a single operation

Updates are performed in the order provided. If an update fails, it’s recorded in the failed list but doesn’t stop other updates.

§Arguments
  • operations - List of update operations to perform
§Returns

Result containing successful updates and failures

Source

pub fn batch_add_styles(&mut self, batch: StyleBatch<'a>) -> Vec<usize>

Add multiple styles in a single operation

Creates the styles section if it doesn’t exist.

§Arguments
  • batch - Batch of styles to add
§Returns

Indices of the added styles within the styles section

Source

pub fn batch_add_events(&mut self, batch: EventBatch<'a>) -> Vec<usize>

Add multiple events in a single operation

Creates the events section if it doesn’t exist.

§Arguments
  • batch - Batch of events to add
§Returns

Indices of the added events within the events section

Source

pub fn atomic_batch_update( &mut self, updates: Vec<UpdateOperation<'a>>, style_additions: Option<StyleBatch<'a>>, event_additions: Option<EventBatch<'a>>, ) -> Result<(), ParseError>

Apply a batch of mixed operations atomically

All operations are validated first. If any validation fails, no changes are made. This provides transactional semantics.

§Arguments
  • updates - Line updates to perform
  • style_additions - Styles to add
  • event_additions - Events to add
§Returns

Ok if all operations succeed, Err with the first validation error

§Errors

Returns error if any operation would fail, without making changes

Source

pub fn enable_change_tracking(&mut self)

Enable change tracking

When enabled, all modifications to the script will be recorded in the change tracker for later analysis.

Source

pub fn disable_change_tracking(&mut self)

Disable change tracking

When disabled, modifications will not be recorded.

Source

pub const fn is_change_tracking_enabled(&self) -> bool

Check if change tracking is enabled

Source

pub fn changes(&self) -> &[Change<'a>]

Get all recorded changes

Returns a slice of all changes recorded since tracking was enabled or since the last clear operation.

Source

pub fn clear_changes(&mut self)

Clear all recorded changes

Removes all changes from the tracker while keeping tracking enabled/disabled.

Source

pub fn change_count(&self) -> usize

Get the number of recorded changes

Source

pub fn diff(&self, other: &Self) -> Vec<Change<'a>>

Compute the difference between this script and another

Analyzes the differences between two scripts and returns a list of changes that would transform the other script into this one.

§Arguments
  • other - The script to compare against
§Returns

A vector of changes representing the differences

Source

pub fn affected_sections(&self, change: &TextChange) -> Vec<SectionType>

Determine which sections are affected by a text change

§Arguments
  • change - The text change to analyze
§Returns

A vector of section types that are affected by the change

Source

pub fn parse_line_in_section( &self, section_type: SectionType, line: &'a str, line_number: u32, ) -> Result<LineContent<'a>>

Parse line in section context

Parses a single line knowing its section context, using stored format information.

§Arguments
  • section_type - The type of section containing this line
  • line - The line text to parse
  • line_number - Line number for error reporting
§Returns

Parsed line content or error

§Errors

Returns ParseError::MissingFormat if format information is missing Returns other parse errors from line-specific parsers

Source

pub fn parse_incremental( &self, new_source: &'a str, change: &TextChange, ) -> Result<Self>

Parse only changed portions and create new Script

This method performs incremental parsing by identifying affected sections and reparsing only those sections while preserving others.

§Arguments
  • new_source - The complete new source text after the change
  • change - Description of what changed in the text
§Returns

A new Script with the changes applied

§Errors

Returns parse errors if affected sections cannot be reparsed

Source

pub fn to_ass_string(&self) -> String

Convert script to ASS string representation

Generates the complete ASS script with all sections in order. Respects the stored format lines for styles and events if available.

§Examples
let script = Script::parse("[Script Info]\nTitle: Test").unwrap();
let ass_string = script.to_ass_string();
assert!(ass_string.contains("[Script Info]"));
assert!(ass_string.contains("Title: Test"));

Trait Implementations§

Source§

impl<'a> Clone for Script<'a>

Source§

fn clone(&self) -> Script<'a>

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<'a> Debug for Script<'a>

Source§

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

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

impl<'a> PartialEq for Script<'a>

Source§

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

Source§

impl<'a> StructuralPartialEq for Script<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Script<'a>

§

impl<'a> RefUnwindSafe for Script<'a>

§

impl<'a> Send for Script<'a>

§

impl<'a> Sync for Script<'a>

§

impl<'a> Unpin for Script<'a>

§

impl<'a> UnwindSafe for Script<'a>

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