import Foundation public enum ShareText { /// Item providers can materialize plain text as BOM-tagged UTF-16. /// Read at most twice the UTF-8 limit, then enforce the actual message bound. public static func decode(_ data: Data) throws -> String { guard data.count <= 32 * 1024 + 2 else { throw AttachmentFailure.tooLarge } if data.starts(with: Data("bplist".utf8)) { // Foundation item providers materialize NSString using a secure // archive. Permit that one class, never arbitrary provider objects. guard let text = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSString.self, from: data) as String? else { throw AttachmentFailure.type } guard text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } return text } let encoding: String.Encoding = data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) ? .utf16 : .utf8 guard let text = String(data: data, encoding: encoding) else { throw AttachmentFailure.type } guard text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } return text } }