Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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