diff --git a/Sources/Library/Schema/Values/String.Encoding+JSONCodable.swift b/Sources/Library/Schema/Values/String.Encoding+JSONCodable.swift index 3d4ce80..cdb27c3 100644 --- a/Sources/Library/Schema/Values/String.Encoding+JSONCodable.swift +++ b/Sources/Library/Schema/Values/String.Encoding+JSONCodable.swift @@ -96,7 +96,8 @@ extension String.Encoding: XCJSON.Codable { if let stringRepresentation { try stringRepresentation.encode(with: coder) } else { - try Int(rawValue).encode(with: coder) + let value = try Int(exactly: rawValue).unwrap(orThrow: "Unsupported text encoding \(rawValue)") + try value.encode(with: coder) } } @@ -104,7 +105,9 @@ extension String.Encoding: XCJSON.Codable { if coder.currentNodeType == .string { self = try StringRepresentation(with: coder).memoryRepresentation } else { - self = try Self(rawValue: UInt(Int(with: coder))) + let value = try Int(with: coder) + let rawValue = try UInt(exactly: value).unwrap(orThrow: "Invalid text encoding \(value)") + self = Self(rawValue: rawValue) } } } diff --git a/Sources/Tests/TextEncodingTests.swift b/Sources/Tests/TextEncodingTests.swift new file mode 100644 index 0000000..9f1038b --- /dev/null +++ b/Sources/Tests/TextEncodingTests.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// Copyright © 2026 Apple Inc. and the xcode-project-format project authors +// +// Licensed under Apache License v2.0 +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + + +import XcodeProjectFormat +import Foundation +import Testing + +struct TextEncodingTests { + @Test func decodingAnOutOfRangeIntegerThrows() { + #expect(throws: NSError.self) { + let _: XCSchema.TextEncoding = try XCJSON.Decoder.decode(data: Data("-1".utf8)) + } + #expect(throws: NSError.self) { + let _: XCSchema.TextEncoding = try XCJSON.Decoder.decode(data: Data("9223372036854775808".utf8)) + } + } + + @Test func encodingAnOutOfRangeRawValueThrows() { + #expect(throws: NSError.self) { + _ = try XCJSON.Encoder.data(for: XCSchema.TextEncoding(rawValue: String.Encoding(rawValue: UInt.max)), options: .defaultOptions) + } + } +}