Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active January 25, 2021 20:50
Show Gist options
  • Save jasdev/59342c18a99b2c5b3c797e7fac37ba43 to your computer and use it in GitHub Desktop.
Save jasdev/59342c18a99b2c5b3c797e7fac37ba43 to your computer and use it in GitHub Desktop.
UTF-8-aligned start to an SRT subtitle group parser.
let timecodeHours = Prefix(2).pipe(Int.parser(isSigned: false)).utf8 // ⇐
let timecodeMinutes = Prefix(2).pipe(Int.parser(isSigned: false)).utf8 // ⇐
let timecodeSeconds = Prefix(2).pipe(Int.parser(isSigned: false)).utf8 // ⇐
let timecodeMilliseconds = Prefix(3).pipe(Int.parser(isSigned: false)).utf8 // ⇐
let timecodeParser = timecodeHours
.skip(StartsWith(":".utf8)) // ⇐
.take(timecodeMinutes)
.skip(StartsWith(":".utf8)) // ⇐
.take(timecodeSeconds)
.skip(StartsWith(",".utf8)) // ⇐
.take(timecodeMilliseconds)
.map { hours, minutes, seconds, milliseconds -> TimeInterval in
let hoursInSeconds = Double(hours) * 60 * 60
let minutesInSeconds = Double(minutes) * 60
let millisecondsInSeconds = Double(milliseconds) * 1 / 1_000
return hoursInSeconds + minutesInSeconds + Double(seconds) + millisecondsInSeconds
}
let timecodeLineParser = timecodeParser
.skip(StartsWith(" --> ".utf8)) // ⇐
.take(timecodeParser)
let srtGroupParser = Int.parser(isSigned: false)
.skip(Newline())
.take(timecodeLineParser)
.skip(Newline()) // ✅ Back in compilin’ order.
// …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment