From 81eaddd6cbf5675136dc0e038c8c0a5cc544ca63 Mon Sep 17 00:00:00 2001 From: Blake Latchford Date: Thu, 19 Nov 2026 13:51:14 -0500 Subject: [PATCH] fix: decode MECP with the top-level 1.4.0 message pattern - Reject a bunch of formatting failures that the spec defines as 'not MECP'. - Strip a trailing newline on decode. - Free text is returned unmodified, so runs of spaces are no longer collapsed. First commit in a series for issue #494 --- .../Sources/MC1Services/MECP/MECPDecode.swift | 64 +++++---------- .../MC1ServicesTests/MECPDecodeTests.swift | 80 +++++++++++++------ 2 files changed, 78 insertions(+), 66 deletions(-) diff --git a/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift b/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift index b7dca377e7..8080a6921d 100644 --- a/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift +++ b/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift @@ -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 { @@ -65,12 +59,9 @@ 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" @@ -78,17 +69,6 @@ public enum MECPDecode { 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)? { var index = text.startIndex while index < text.endIndex { diff --git a/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift b/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift index cbf6f17f3a..167d209090 100644 --- a/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift @@ -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 @@ -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) @@ -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)) } }