Skip to content

Commit 1d5a5a9

Browse files
committed
Updated text decoding to prevent lossy UTF8 decoding pre-macOS 15 (orchetect/swift-midi#281)
1 parent 7584a07 commit 1d5a5a9

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

Sources/SwiftMIDIFile/MIDIFileEvent/Events/Event Text.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -489,9 +489,15 @@ extension MIDIFileEvent.Text.EncodingMode {
489489
let data = Data(rawStringBytes)
490490

491491
let isAllASCIIPrintable = data.allSatisfy({ CharacterSet.asciiPrintable.contains(.init($0)) })
492+
let replacementChar = "\u{FFFD}" // Encoded in UTF-8 as 0xEF 0xBF 0xBD
492493

493-
// only allow UTF-8 decoding if necessary
494-
let string: String = if !isAllASCIIPrintable, let text = String(data: data, encoding: .utf8) {
494+
// only allow UTF-8 decoding if necessary and if it does not contain any replacement chars.
495+
// UTF-8 decoding pre-macOS 15 will allow lossy decoding of invalid UTF-8 and use replacement chars
496+
// but we want to avoid that. it's not a problem on macOS 15+.
497+
let string: String = if !isAllASCIIPrintable,
498+
let text = String(data: data, encoding: .utf8),
499+
!text.contains(replacementChar)
500+
{
495501
text
496502
} else if let text = String(data: data, encoding: .nonLossyASCII) {
497503
text

0 commit comments

Comments
 (0)