Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 22 additions & 42 deletions MC1Services/Sources/MC1Services/MECP/MECPDecode.swift
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
/// The MECP wire grammar. A string that does not match returns nil.
public enum MECPDecode {
public static func decode(_ input: String) -> MECPMessage? {
guard input.hasPrefix(prefix) else { return nil }
let severityIndex = input.index(input.startIndex, offsetBy: prefix.count, limitedBy: input.endIndex)
guard let severityIndex, severityIndex < input.endIndex else { return nil }
guard isASCIIDigit(input[severityIndex]),
let severityDigit = input[severityIndex].wholeNumberValue,
let severity = MECPMessage.Severity(rawValue: severityDigit) else {
guard let match = removingLineEnding(input).wholeMatch(of: messagePattern),
let digit = Int(match.1),
let severity = MECPMessage.Severity(rawValue: digit) else {
return nil
}
let codes = match.2.split(separator: " ").map(String.init)
return MECPMessage(severity: severity, codes: codes, freetext: match.3.map(String.init))
}

let bodyOffset = prefix.count + bodyLead
let body = if let bodyIndex = input.index(input.startIndex, offsetBy: bodyOffset, limitedBy: input.endIndex), bodyIndex < input.endIndex {
String(input[bodyIndex...])
} else {
""
}

var codes: [String] = []
var tailTokens: [String] = []
var readingTail = false
for token in body.split(separator: " ", omittingEmptySubsequences: true) {
let text = String(token)
if !readingTail, isCodeToken(text) {
codes.append(text)
} else {
readingTail = true
tailTokens.append(text)
}
}

let freetext = tailTokens.isEmpty ? nil : tailTokens.joined(separator: " ")
return MECPMessage(severity: severity, codes: codes, freetext: freetext)
/// MECP 1.4.0 §6.1, as written in the protocol's freetext/patterns.json: a severity, one or more
/// codes separated by single spaces, and optional free text after one more space that does not
/// begin or end with a space or tab and has no line break in it. Matched by Unicode scalar, as the
/// pattern is in other languages: by `Character`, a CRLF is one character that the line-break
/// classes do not exclude.
///
/// Marked `nonisolated(unsafe)` because `Regex` is not `Sendable`; it is an immutable value.
private nonisolated(unsafe) static let messagePattern = #/^MECP/([0-3])/([A-Z][0-9]{2}(?: [A-Z][0-9]{2})*)(?: ([^ \t\n\f\r\u0085\u2028\u2029](?:[^\n\f\r\u0085\u2028\u2029]*[^ \t\n\f\r\u0085\u2028\u2029])?))?$/#
.matchingSemantics(.unicodeScalar)

/// MECP §6.1: before matching, a decoder removes at most one trailing line ending: `\n`, `\r` or `\r\n`.
private static func removingLineEnding(_ input: String) -> String {
var scalars = Substring(input).unicodeScalars
if scalars.last == "\n" { scalars.removeLast() }
if scalars.last == "\r" { scalars.removeLast() }
return String(scalars)
}

struct Extraction: Equatable {
Expand Down Expand Up @@ -65,30 +59,16 @@ public enum MECPDecode {
return extraction
}

private static let prefix = "MECP/"
private static let bodyLead = 2
private static let etaCode = "R03"
private static let maxHour = 23
private static let maxMinute = 59
private static let codeLength = 3
private static let clockDigits = 4
private static let paxSuffix = "pax"

private static func isASCIIDigit(_ character: Character) -> Bool {
character.isASCII && character.isNumber
}

private static func isCodeToken(_ token: String) -> Bool {
guard token.count == codeLength else { return false }
var characters = token.makeIterator()
guard let letter = characters.next(), letter.isASCII, letter.isUppercase, letter.isLetter,
let tens = characters.next(), isASCIIDigit(tens),
let ones = characters.next(), isASCIIDigit(ones) else {
return false
}
return true
}

private static func firstPax(in text: String) -> (count: Int, range: Range<String.Index>)? {
var index = text.startIndex
while index < text.endIndex {
Expand Down
80 changes: 56 additions & 24 deletions MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,13 @@ struct MECPDecodeTests {
}

@Test
func `a valid severity is a message when the slash is missing`() throws {
let bare = try #require(MECPDecode.decode("MECP/0"))
#expect(bare.severity == .mayday)
#expect(bare.codes.isEmpty)
#expect(bare.freetext == nil)

let skippedDelimiter = try #require(MECPDecode.decode("MECP/0XM01"))
#expect(skippedDelimiter.codes == ["M01"])
#expect(skippedDelimiter.freetext == nil)

let emptyBody = try #require(MECPDecode.decode("MECP/0/"))
#expect(emptyBody.codes.isEmpty)
#expect(emptyBody.freetext == nil)
func `a message needs the slash after the severity and at least one code`() {
#expect(MECPDecode.decode("MECP/0") == nil)
#expect(MECPDecode.decode("MECP/0XM01") == nil)
#expect(MECPDecode.decode("MECP/0/") == nil)
#expect(MECPDecode.decode("MECP/01/M01") == nil)
#expect(MECPDecode.decode("MECP/1/t05 x") == nil)
#expect(MECPDecode.decode("MECP/0/M011") == nil)
}

@Test
Expand All @@ -47,19 +41,57 @@ struct MECPDecodeTests {
}

@Test
func `empty tokens are dropped before the code scan`() throws {
let message = try #require(MECPDecode.decode("MECP/0/M01 M02"))
#expect(message.codes == ["M01", "M02"])
#expect(message.freetext == nil)
func `codes and free text are separated by exactly one space`() {
#expect(MECPDecode.decode("MECP/0/M01 M02") == nil)
#expect(MECPDecode.decode("MECP/0/M01\tM02") == nil)
#expect(MECPDecode.decode("MECP/0/M01\u{A0}help") == nil)
#expect(MECPDecode.decode("MECP/1/R03 15") == nil)
#expect(MECPDecode.decode("MECP/1/T05 ") == nil)
#expect(MECPDecode.decode("MECP/1/T05 help ") == nil)
#expect(MECPDecode.decode("MECP/1/T05 help\t") == nil)
}

@Test
func `a repeated space before an R03 eta still fills eta and clears the tail`() throws {
let message = try #require(MECPDecode.decode("MECP/1/R03 15"))
#expect(message.codes == ["R03"])
#expect(message.eta == 15)
#expect(message.displayTail == nil)
func `a code-shaped word that is not a whole code starts the free text`() throws {
let glued = try #require(MECPDecode.decode("MECP/1/T05 T05x"))
#expect(glued.codes == ["T05"])
#expect(glued.freetext == "T05x")

let spaced = try #require(MECPDecode.decode("MECP/1/T05 T05 x"))
#expect(spaced.codes == ["T05"])
#expect(spaced.freetext == "T05 x")
}

@Test
func `free text is kept as sent`() throws {
let message = try #require(MECPDecode.decode("MECP/3/L01 see you\tthere"))
#expect(message.freetext == "see you\tthere")
}

@Test
func `one trailing line ending is removed before matching`() throws {
for input in ["MECP/2/B03\n", "MECP/2/B03\r", "MECP/2/B03\r\n"] {
let message = try #require(MECPDecode.decode(input))
#expect(message.codes == ["B03"])
#expect(message.freetext == nil)
}
let text = try #require(MECPDecode.decode("MECP/3/L01 see you\r\n"))
#expect(text.freetext == "see you")

#expect(MECPDecode.decode("MECP/2/B03\n\n") == nil)
#expect(MECPDecode.decode("MECP/2/B03\n\r") == nil)
#expect(MECPDecode.decode("MECP/2/B03\r\n\r\n") == nil)
}

@Test
func `a line break inside the message is not MECP`() {
for lineBreak in ["\n", "\r", "\r\n", "\u{0C}", "\u{85}", "\u{2028}", "\u{2029}"] {
#expect(MECPDecode.decode("MECP/3/L01 a\(lineBreak)b") == nil)
}
}

@Test
func `an R03 eta fills eta and clears the tail`() throws {
let spaced = try #require(MECPDecode.decode("MECP/1/R03 15"))
#expect(spaced.eta == 15)
#expect(spaced.displayTail == nil)
Expand Down Expand Up @@ -87,10 +119,10 @@ struct MECPDecodeTests {
@Test
func `decode keeps a string longer than the sender byte budget`() throws {
#expect(MECPMessage.maxUTF8Bytes == 200)
let input = "MECP/0/" + String(repeating: "A", count: MECPMessage.maxUTF8Bytes)
let input = "MECP/0/M01 " + String(repeating: "A", count: MECPMessage.maxUTF8Bytes)
let message = try #require(MECPDecode.decode(input))
#expect(message.severity == .mayday)
#expect(message.codes.isEmpty)
#expect(message.codes == ["M01"])
#expect(message.freetext == String(repeating: "A", count: MECPMessage.maxUTF8Bytes))
}
}
Loading