Skip to content

Commit a71a47f

Browse files
authored
PropertyListEncoder should encode whole-value reals in XML without the .0 suffix for backward compatibility (#718)
1 parent 1bdf2fb commit a71a47f

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Sources/FoundationEssentials/PropertyList/XMLPlistEncodingFormat.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,14 @@ struct _XMLPlistEncodingFormat : PlistEncodingFormat {
10011001
return "-infinity"
10021002
}
10031003
}
1004-
return val.description
1004+
// Historically whole-value reals (2.0, -5.0, etc) are
1005+
// encoded without the `.0` suffix.
1006+
// JSONEncoder also has the same behavior. See `JSONWriter.swift`
1007+
var string = val.description
1008+
if string.hasSuffix(".0") {
1009+
string.removeLast(2)
1010+
}
1011+
return string
10051012
}
10061013

10071014
mutating func appendDate(_ date: Date) {

Tests/FoundationEssentialsTests/PropertyListEncoderTests.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,6 +1055,36 @@ data1 = <7465
10551055
XCTAssertEqual(d.timeIntervalSinceReferenceDate, -63145612800)
10561056
}
10571057

1058+
func test_realEncodeRemoveZeroSuffix() throws {
1059+
// Tests that we encode "whole-value reals" (such as `2.0`, `-5.0`, etc)
1060+
// **without** the `.0` for backwards compactability
1061+
let encoder = PropertyListEncoder()
1062+
encoder.outputFormat = .xml
1063+
let template = "\(_XMLPlistEncodingFormat.Writer.header)<array>\n\t<real><%EXPECTED%></real>\n</array>\n</plist>\n"
1064+
1065+
let wholeFloat: Float = 2.0
1066+
var data = try encoder.encode([wholeFloat])
1067+
var str = try XCTUnwrap(String(data: data, encoding: String.Encoding.utf8))
1068+
var expected = template.replacingOccurrences(
1069+
of: "<%EXPECTED%>", with: "2")
1070+
XCTAssertEqual(str, expected)
1071+
1072+
let wholeDouble: Double = -5.0
1073+
data = try encoder.encode([wholeDouble])
1074+
str = try XCTUnwrap(String(data: data, encoding: String.Encoding.utf8))
1075+
expected = template.replacingOccurrences(
1076+
of: "<%EXPECTED%>", with: "-5")
1077+
XCTAssertEqual(str, expected)
1078+
1079+
// Make sure other reals are not affacted
1080+
let notWholeDouble = 0.5
1081+
data = try encoder.encode([notWholeDouble])
1082+
str = try XCTUnwrap(String(data: data, encoding: String.Encoding.utf8))
1083+
expected = template.replacingOccurrences(
1084+
of: "<%EXPECTED%>", with: "0.5")
1085+
XCTAssertEqual(str, expected)
1086+
}
1087+
10581088
func test_farFutureDates() throws {
10591089
let date = Date(timeIntervalSince1970: 999999999999.0)
10601090

0 commit comments

Comments
 (0)