Skip to content

Fix UB when hashing some doubles in 32bits. #1680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CoreFoundation/Base.subproj/ForFoundationOnly.h
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ CF_INLINE CFHashCode _CFHashDouble(const double d) {
result += -((CFHashCode)(fabs(fractional)));
} else if (fractional > 0) {
// Caveat: the > 0 is incredibly important [28612173]
result += fractional;
result += (CFHashCode)fractional;
}
return result;
}
Expand Down
23 changes: 23 additions & 0 deletions TestFoundation/TestNSNumber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class TestNSNumber : XCTestCase {
("test_stringValue", test_stringValue),
("test_Equals", test_Equals),
("test_boolValue", test_boolValue),
("test_hash", test_hash),
]
}

Expand Down Expand Up @@ -1262,4 +1263,26 @@ class TestNSNumber : XCTestCase {
XCTAssertEqual(NSNumber(value: Int.min + 1).boolValue, true)
XCTAssertEqual(NSNumber(value: Int(-1)).boolValue, true)
}

func test_hash() {
// A zero double hashes as zero.
XCTAssertEqual(NSNumber(value: 0 as Double).hash, 0)

// A positive double without fractional part should hash the same as the
// equivalent 64 bit number.
XCTAssertEqual(NSNumber(value: 123456 as Double).hash, NSNumber(value: 123456 as Int64).hash)

// A negative double without fractional part should hash the same as the
// equivalent 64 bit number.
XCTAssertEqual(NSNumber(value: -123456 as Double).hash, NSNumber(value: -123456 as Int64).hash)

#if arch(i386) || arch(arm)
// This test used to fail in 32 bit platforms.
XCTAssertNotEqual(NSNumber(value: 551048378.24883795 as Double).hash, 0)

// Some hashes are correctly zero, though. Like the following which
// was found by trial and error.
XCTAssertEqual(NSNumber(value: 1.3819660135 as Double).hash, 0)
#endif
}
}