forge
Explore
Log in

Don't you dare go Hollow

S13: ec-subs markup Tree struct replaces the Option-bottom stack and its unwraps; Dialect enum replaces the webvtt bool (same operations)

Browse files at this commit

5442b3dcca9ac32eaf862e6ef47a96959d2bbb58Ahmet Kaan GümüşParent: f75aa7d
crates/ec-subs/src/markup.rsmodified+91 -89
@@ -86,70 +86,119 @@ pub fn parse_clock(field: &str) -> Option<i64> {
8686 /// quadratic to close or the tree too deep to walk.
8787 const MAX_NEST: usize = 64;
8888
89-/// One cue body's markup as runs. `webvtt` turns on the two tags only WebVTT
89+/// Which markup a cue body is written in.
90+#[derive(Clone, Copy, PartialEq, Eq)]
91+pub(crate) enum Dialect {
92+ Srt,
93+ WebVtt,
94+}
95+
96+/// The cue being built: its top-level runs, and the open tags above them, innermost last.
97+#[derive(Default)]
98+struct Tree {
99+ root: Vec<Segment>,
100+ open: Vec<(Open, Vec<Segment>)>,
101+}
102+
103+impl Tree {
104+ fn top(&mut self) -> &mut Vec<Segment> {
105+ match self.open.last_mut() {
106+ Some((_, children)) => children,
107+ None => &mut self.root,
108+ }
109+ }
110+
111+ fn close_top(&mut self) {
112+ let Some((open, children)) = self.open.pop() else {
113+ return;
114+ };
115+ let parent = self.top();
116+ match open.name.as_str() {
117+ "b" => parent.push(Segment::Bold(children)),
118+ "i" => parent.push(Segment::Italic(children)),
119+ "u" => parent.push(Segment::Underline(children)),
120+ "s" => parent.push(Segment::Strike(children)),
121+ "v" => parent.push(Segment::Voice {
122+ name: open.annotation,
123+ children,
124+ }),
125+ "c" => parent.push(Segment::Class {
126+ name: open.annotation,
127+ children,
128+ }),
129+ _ => {
130+ if let Some(rgb) = open.color {
131+ parent.push(Segment::Color { rgb, children });
132+ } else if open.family.is_some() || open.size.is_some() {
133+ parent.push(Segment::Font {
134+ family: open.family,
135+ size: open.size,
136+ children,
137+ });
138+ } else {
139+ parent.extend(children);
140+ }
141+ }
142+ }
143+ }
144+}
145+
146+/// One cue body's markup as runs. `WebVtt` turns on the two tags only WebVTT
90147 /// has — `<v>` and `<c>` — and the inline timestamps that go with them.
91-pub(crate) fn parse_inline(body: &str, webvtt: bool) -> Vec<Segment> {
92- // A stack of open tags, each with the children collected inside it so far;
93- // the bottom frame is the cue itself and can never be popped.
94- let mut stack: Vec<(Option<Open>, Vec<Segment>)> = vec![(None, Vec::new())];
148+pub(crate) fn parse_inline(body: &str, dialect: Dialect) -> Vec<Segment> {
149+ let mut tree = Tree::default();
95150 let mut text = String::new();
96151 let mut rest = body;
97152 while let Some(at) = rest.find('<') {
98153 text.push_str(&unescape(&rest[..at]));
99154 let after = &rest[at + 1..];
100155 let Some(end) = after.find('>') else {
101- // No closing bracket anywhere: the rest of the cue is text.
102156 text.push_str(&unescape(&rest[at..]));
103157 rest = "";
104158 break;
105159 };
106160 let tag = &after[..end];
107161 rest = &after[end + 1..];
108- match classify(tag, webvtt) {
162+ match classify(tag, dialect) {
109163 Tag::Text => {
110164 text.push('<');
111165 text.push_str(&unescape(tag));
112166 text.push('>');
113167 }
114168 Tag::Timestamp(offset_us) => {
115- flush(&mut text, &mut stack);
116- push(&mut stack, Segment::Timestamp { offset_us });
169+ flush(&mut text, &mut tree);
170+ tree.top().push(Segment::Timestamp { offset_us });
117171 }
118172 Tag::Raw => {
119- flush(&mut text, &mut stack);
120- push(&mut stack, Segment::Raw(format!("<{tag}>")));
173+ flush(&mut text, &mut tree);
174+ tree.top().push(Segment::Raw(format!("<{tag}>")));
121175 }
122176 Tag::Open(open) => {
123- flush(&mut text, &mut stack);
124- if stack.len() <= MAX_NEST {
125- stack.push((Some(open), Vec::new()));
177+ flush(&mut text, &mut tree);
178+ if tree.open.len() < MAX_NEST {
179+ tree.open.push((open, Vec::new()));
126180 }
127181 }
128182 Tag::Close(name) => {
129- flush(&mut text, &mut stack);
183+ flush(&mut text, &mut tree);
130184 // Close the innermost frame with that name, and everything
131185 // inside it: `<b><i></b>` closes both, which is what a browser
132186 // does with the same bytes.
133- let found = stack
134- .iter()
135- .rposition(|(open, _)| open.as_ref().is_some_and(|o| o.name == name));
187+ let found = tree.open.iter().rposition(|(open, _)| open.name == name);
136188 if let Some(depth) = found {
137- while stack.len() > depth {
138- close_top(&mut stack);
189+ while tree.open.len() > depth {
190+ tree.close_top();
139191 }
140192 }
141193 }
142194 }
143195 }
144196 text.push_str(&unescape(rest));
145- flush(&mut text, &mut stack);
146- while stack.len() > 1 {
147- close_top(&mut stack);
197+ flush(&mut text, &mut tree);
198+ while !tree.open.is_empty() {
199+ tree.close_top();
148200 }
149- stack
150- .pop()
151- .map(|(_, children)| children)
152- .unwrap_or_default()
201+ tree.root
153202 }
154203
155204 /// An open tag: its name and the arguments the closing wrapper will need.
@@ -170,7 +219,7 @@ enum Tag {
170219 Text,
171220 }
172221
173-fn classify(tag: &str, webvtt: bool) -> Tag {
222+fn classify(tag: &str, dialect: Dialect) -> Tag {
174223 let trimmed = tag.trim();
175224 if trimmed.is_empty() {
176225 return Tag::Text;
@@ -181,7 +230,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag {
181230 return Tag::Close(name);
182231 }
183232 // `<00:00:01.500>` is a cue timestamp, not an element.
184- if webvtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) {
233+ if dialect == Dialect::WebVtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) {
185234 return match parse_clock(trimmed) {
186235 Some(offset_us) => Tag::Timestamp(offset_us),
187236 None => Tag::Text,
@@ -211,7 +260,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag {
211260 size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()),
212261 annotation: String::new(),
213262 }),
214- "v" | "c" if webvtt => Tag::Open(Open {
263+ "v" | "c" if dialect == Dialect::WebVtt => Tag::Open(Open {
215264 annotation: match name.as_str() {
216265 "v" => attrs.trim().to_owned(),
217266 _ => classes.replace('.', " "),
@@ -350,22 +399,17 @@ fn unescape(text: &str) -> String {
350399 out
351400 }
352401
353-fn flush(text: &mut String, stack: &mut [(Option<Open>, Vec<Segment>)]) {
402+fn flush(text: &mut String, tree: &mut Tree) {
354403 if !text.is_empty() {
355404 let taken = std::mem::take(text);
356- // A newline inside a cue body is a line break, not whitespace.
357405 let mut lines = taken.split('\n');
358406 if let Some(first) = lines.next()
359407 && !first.is_empty()
360408 {
361- stack
362- .last_mut()
363- .unwrap()
364- .1
365- .push(Segment::Text(first.into()));
409+ tree.top().push(Segment::Text(first.into()));
366410 }
367411 for line in lines {
368- let children = &mut stack.last_mut().unwrap().1;
412+ let children = tree.top();
369413 children.push(Segment::LineBreak);
370414 if !line.is_empty() {
371415 children.push(Segment::Text(line.into()));
@@ -374,48 +418,6 @@ fn flush(text: &mut String, stack: &mut [(Option<Open>, Vec<Segment>)]) {
374418 }
375419 }
376420
377-fn push(stack: &mut [(Option<Open>, Vec<Segment>)], segment: Segment) {
378- stack.last_mut().unwrap().1.push(segment);
379-}
380-
381-fn close_top(stack: &mut Vec<(Option<Open>, Vec<Segment>)>) {
382- let Some((open, children)) = stack.pop() else {
383- return;
384- };
385- let Some(open) = open else { return };
386- let parent = &mut stack.last_mut().unwrap().1;
387- match open.name.as_str() {
388- "b" => parent.push(Segment::Bold(children)),
389- "i" => parent.push(Segment::Italic(children)),
390- "u" => parent.push(Segment::Underline(children)),
391- "s" => parent.push(Segment::Strike(children)),
392- "v" => parent.push(Segment::Voice {
393- name: open.annotation,
394- children,
395- }),
396- "c" => parent.push(Segment::Class {
397- name: open.annotation,
398- children,
399- }),
400- // `<font>`: whichever of colour and face/size it stated. One that
401- // stated neither is a frame with nothing to say, so it is unwrapped
402- // rather than kept as an empty node.
403- _ => {
404- if let Some(rgb) = open.color {
405- parent.push(Segment::Color { rgb, children });
406- } else if open.family.is_some() || open.size.is_some() {
407- parent.push(Segment::Font {
408- family: open.family,
409- size: open.size,
410- children,
411- });
412- } else {
413- parent.extend(children);
414- }
415- }
416- }
417-}
418-
419421 #[cfg(test)]
420422 mod tests {
421423 use super::*;
@@ -446,33 +448,33 @@ mod tests {
446448
447449 #[test]
448450 fn markup_nests_and_forgives() {
449- let segments = parse_inline("<i>a</i> <b>b", false);
451+ let segments = parse_inline("<i>a</i> <b>b", Dialect::Srt);
450452 assert_eq!(plain_text(&segments), "a b");
451453 assert!(matches!(segments[0], Segment::Italic(_)));
452454 assert!(matches!(segments[2], Segment::Bold(_)));
453455 // Mismatched close, stray close, and a `<` that is just a `<`.
454- assert_eq!(plain_text(&parse_inline("<b><i>x</b>y", false)), "xy");
455- assert_eq!(plain_text(&parse_inline("</i>plain", false)), "plain");
456- assert_eq!(plain_text(&parse_inline("a < b", false)), "a < b");
456+ assert_eq!(plain_text(&parse_inline("<b><i>x</b>y", Dialect::Srt)), "xy");
457+ assert_eq!(plain_text(&parse_inline("</i>plain", Dialect::Srt)), "plain");
458+ assert_eq!(plain_text(&parse_inline("a < b", Dialect::Srt)), "a < b");
457459 assert_eq!(
458- plain_text(&parse_inline("2 &lt; 3 &amp; 4", false)),
460+ plain_text(&parse_inline("2 &lt; 3 &amp; 4", Dialect::Srt)),
459461 "2 < 3 & 4"
460462 );
461463 }
462464
463465 #[test]
464466 fn webvtt_only_tags_are_off_for_srt() {
465- let vtt = parse_inline("<v Ann>hi</v>", true);
467+ let vtt = parse_inline("<v Ann>hi</v>", Dialect::WebVtt);
466468 assert!(matches!(vtt[0], Segment::Voice { .. }));
467469 assert_eq!(plain_text(&vtt), "hi");
468- let srt = parse_inline("<v Ann>hi", false);
470+ let srt = parse_inline("<v Ann>hi", Dialect::Srt);
469471 assert_eq!(plain_text(&srt), "hi");
470472 assert!(matches!(srt[0], Segment::Raw(_)));
471473 }
472474
473475 #[test]
474476 fn font_colour_is_read_by_hex_and_by_name() {
475- let segments = parse_inline("<font color=\"#ff0000\">red</font>", false);
477+ let segments = parse_inline("<font color=\"#ff0000\">red</font>", Dialect::Srt);
476478 assert!(matches!(
477479 segments[0],
478480 Segment::Color {
@@ -480,7 +482,7 @@ mod tests {
480482 ..
481483 }
482484 ));
483- let named = parse_inline("<font color=lime>green</font>", false);
485+ let named = parse_inline("<font color=lime>green</font>", Dialect::Srt);
484486 assert!(matches!(
485487 named[0],
486488 Segment::Color {
crates/ec-subs/src/srt.rsmodified+2 -2
@@ -10,7 +10,7 @@
1010 use ec_core::{Error, Result};
1111
1212 use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack};
13-use crate::markup::{decode, parse_clock, parse_inline};
13+use crate::markup::{decode, parse_clock, parse_inline, Dialect};
1414
1515 /// Parse a SubRip document.
1616 ///
@@ -40,7 +40,7 @@ pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
4040 end_us: end_us.max(start_us),
4141 style_ref: None,
4242 positioning: None,
43- segments: parse_inline(body.trim_end(), false),
43+ segments: parse_inline(body.trim_end(), Dialect::Srt),
4444 });
4545 }
4646 if track.cues.is_empty() && text.split_whitespace().next().is_some() {
crates/ec-subs/src/webvtt.rsmodified+2 -2
@@ -9,7 +9,7 @@
99 use ec_core::{Error, Result};
1010
1111 use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign};
12-use crate::markup::{decode, parse_inline};
12+use crate::markup::{decode, parse_inline, Dialect};
1313 use crate::srt::timing;
1414
1515 /// Parse a WebVTT document.
@@ -57,7 +57,7 @@ pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
5757 end_us: end_us.max(start_us),
5858 style_ref: None,
5959 positioning: settings(lines[at]),
60- segments: parse_inline(body.trim_end(), true),
60+ segments: parse_inline(body.trim_end(), Dialect::WebVtt),
6161 });
6262 }
6363 if track.cues.is_empty() && text.split_whitespace().next().is_some() {