Skip to content
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
32 changes: 32 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Sample code to reproduce the behavior.

```swift
Sample code goes here
```

**Expected behavior**
A clear and concise description of what you expected to happen.

**Configuration (please complete the following information):**
- Swift Version: [e.g. Swift 6.1, `main` branch under development, etc]
- OS: [e.g. iOS, macOS, Linux Distribution, Windows, Android]
- OS Version: [e.g. iOS 18]

**Regression information:**
If applicable, please list older versions where this issue did not occur.

**Additional context**
Add any other context about the problem here.
17 changes: 17 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
name: Feature request
about: Request a new API or other enhancement
title: ''
labels: enhancement
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is.

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Additional context**
Add any other context about the feature request here.
3 changes: 3 additions & 0 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ name: Pull request
on:
pull_request:
types: [opened, reopened, synchronize]
paths-ignore:
- '*.md'
- 'Proposals/**'

jobs:
tests:
Expand Down
87 changes: 87 additions & 0 deletions Benchmarks/Benchmarks/Essentials/BenchmarkEssentials.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,91 @@ let benchmarks = {
assert(u1 != u2)
}
}

// MARK: Data

func createSomeData(_ length: Int) -> Data {
var d = Data(repeating: 42, count: length)
// Set a byte to be another value just so we know we have a unique pointer to the backing
// For maximum inefficiency in the not equal case, set the last byte
d[length - 1] = UInt8.random(in: UInt8.min..<UInt8.max)
return d
}

/// A box `Data`. Intentionally turns the value type into a reference, so we can make a promise that the inner value is not copied due to mutation during a test of insertion or replacing.
class TwoDatasBox {
var d1: Data
var d2: Data

init(d1: Data, d2: Data) {
self.d1 = d1
self.d2 = d2
}
}

// MARK: -

Benchmark("DataEqualEmpty", closure: { benchmark, box in
blackHole(box.d1 == box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = Data()
let d2 = d1
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataEqualInline", closure: { benchmark, box in
blackHole(box.d1 == box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(12) // Less than size of InlineData.Buffer
let d2 = d1
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataNotEqualInline", closure: { benchmark, box in
blackHole(box.d1 != box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(12) // Less than size of InlineData.Buffer
let d2 = createSomeData(12)
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataEqualLarge", closure: { benchmark, box in
blackHole(box.d1 == box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(1024 * 8)
let d2 = d1
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataNotEqualLarge", closure: { benchmark, box in
blackHole(box.d1 != box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(1024 * 8)
let d2 = createSomeData(1024 * 8)
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataEqualReallyLarge", closure: { benchmark, box in
blackHole(box.d1 == box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(1024 * 1024 * 8)
let d2 = d1
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

Benchmark("DataNotEqualReallyLarge", closure: { benchmark, box in
blackHole(box.d1 != box.d2)
}, setup: { () -> TwoDatasBox in
let d1 = createSomeData(1024 * 1024 * 8)
let d2 = createSomeData(1024 * 1024 * 8)
let box = TwoDatasBox(d1: d1, d2: d2)
return box
})

}
54 changes: 4 additions & 50 deletions Evolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ A group of core contributors and stakeholders form the _Foundation Workgroup_, w
*This section outlines the general process for features with a larger scope. For minor API proposals, please refer to the [Abbreviated review for minor proposals](#abbreviated-review-for-minor-proposals) section.*

* **Consider the goal**: Before proposing a change, please consider how your idea fits into the goals and themes for the upcoming release.
* **Socialize the idea**: Propose a rough sketch of the idea in the "pitches" section of the Swift forums, the problems it solves, what the solution looks like, etc., to gauge interest from the community.
* **Socialize the idea**: Propose a rough sketch of the idea on the [Swift forums - Foundation project](https://forums.swift.org/c/related-projects/foundation/99), the problems it solves, what the solution looks like, etc., to gauge interest from the community. Please feel free to include "[Pitch]" in the title.
* **Develop the proposal**: Expand the rough sketch into a complete proposal, using the [proposal template](Proposals/0000-template.md), and continue to refine the proposal on the forums. Prototyping an implementation and its uses along with the proposal is required because it helps ensure both technical feasibility of the proposal as well as validating that the proposal solves the problems it is meant to solve.
* **Request a review**: Initiate a pull request to the swift-foundation repository to indicate to the workgroup that you would like the proposal to be reviewed. When the proposal is sufficiently detailed and clear, and addresses feedback from earlier discussions of the idea, the pull request will be accepted. The proposal will be assigned a proposal number as well as a Foundation Workgroup member to manage the review.
* **Request a review**: Initiate a pull request to the swift-foundation repository to indicate to the workgroup that you would like the proposal to be reviewed. When the proposal is sufficiently detailed and clear, and addresses feedback from earlier discussions of the idea, the pull request will be accepted. The proposal will be assigned a proposal number as well as a Foundation Workgroup member to manage the review. This marks as the start of the review.
* **Address feedback**: In general, and especially during the review period, be responsive to questions and feedback about the proposal.

### The review process
Expand All @@ -22,7 +22,7 @@ The review process for a particular proposal begins when a member of the Foundat

The review manager will work with the proposal authors to schedule the review. Reviews usually last a single week, but can run longer for particularly large or complex proposals.

When the scheduled review period arrives, the review manager will post the proposal to the Swift forums with the proposal title. To avoid delays, it is important that the proposal authors be available to answer questions, address feedback, and clarify their intent during the review period.
When the scheduled review period arrives, the review manager will post the proposal to the [Swift forums - Foundation Project](https://forums.swift.org/c/related-projects/foundation/99) with the proposal title. To avoid delays, it is important that the proposal authors be available to answer questions, address feedback, and clarify their intent during the review period.

After the review has completed, the Foundation Workgroup will make a decision on the proposal. The review manager is responsible for determining consensus among the Foundation Workgroup members, then reporting their decision to the proposal authors and forums. The review manager will update the proposal's state in the repository to reflect that decision.

Expand All @@ -31,53 +31,7 @@ After the review has completed, the Foundation Workgroup will make a decision on
Minor API enhancement ideas that have gained community interest through GitHub issues or forum threads may take a shorter review process. Examples include extending existing types with new functions or variables, or adding new `case` to `enum`. Instead of requiring both a pitch thread and a review, these changes can be proposed directly with a proposal document on a pitch thread. The workgroup has appointed an API champion (currently @itingliu) to oversee this process. Here's what you would do:

* **Develop the proposal**: Prepare the proposal using the [proposal template](Proposals/0000-template.md) with a prototype.
* **Request an abbreviated review**: Initiate a pull request to the swift-foundation repository to indicate to the workgroup that you would like the proposal to be reviewed. Meanwhile, post the pull request on the "pitches" section of the Swift forums. Upon seeing the pitch on the forum, a workgroup member will be assigned to manage the review.
* **Request an abbreviated review**: Initiate a pull request to the swift-foundation repository to indicate to the workgroup that you would like the proposal to be reviewed. Meanwhile, post the content on the [Swift forums - Foundation project](https://forums.swift.org/c/related-projects/foundation/99). Upon seeing the pitch on the forum, a workgroup member will be assigned to manage the review. The review manager will comment in the pitch post if the proposal is deemed suitable for abbreviated review, and communicate the next steps on the pitch post.
* **Address feedback**: Be responsive to questions and feedback and continue to refine the proposal as needed.

At the end of the review period, the review manager will accept the proposal if there is a broad agreement among workgroup members and the community.


### Appendix: Review Announcement Template

(Credit: This section is adapted from [Swift-Evolution's announcement template](https://github.com/apple/swift-evolution/blob/main/process.md#review-announcement))

When a proposal enters review, a new topic will be posted to the [Foundation project of the Swift forums](https://forums.swift.org/c/related-projects/foundation/) using the following template.

<details>
<summary> Template </summary>

---
Hello Swift community,

The review of [\<\<PROPOSAL NAME>>]\(\<\<LINK TO PROPOSAL>>) begins now and runs through \<\<REVIEW END DATE>>

Reviews are an important part of the Swift-Foundation evolution process. All review feedback should be either on this forum thread or, if you would like to keep your feedback private, directly to me as the review manager by \<\<CONTACT METHOD>>. When contacting the review manager directly, please include proposal name in the subject line.


##### Trying it out

If you'd like to try this proposal out, you can check out \<\<LINK TO IMPLEMENTATION>>.

##### What goes into a review?

The goal of the review process is to improve the proposal under review
through constructive criticism and, eventually, determine the direction of
Swift-Foundation. When writing your review, here are some questions you might want to
answer in your review:

* What is your evaluation of the proposal?
* Does this proposal fit well with the feel and direction of Swift-Foundation?
* If you have used other languages or libraries with a similar
feature, how do you feel that this proposal compares to those?
* How much effort did you put into your review? A glance, a quick
reading, or an in-depth study?

More information about Swift-Foundation review process is available at

> <https://github.com/apple/swift-foundation/blob/main/CONTRIBUTING.md>

Thank you,

-\<\<REVIEW MANAGER NAME>>

Review Manager
26 changes: 24 additions & 2 deletions Sources/FoundationEssentials/Data/Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2709,14 +2709,36 @@ public struct Data : Equatable, Hashable, RandomAccessCollection, MutableCollect
/// Returns `true` if the two `Data` arguments are equal.
@inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change.
public static func ==(d1 : Data, d2 : Data) -> Bool {
// See if both are empty
switch (d1._representation, d2._representation) {
case (.empty, .empty):
return true
default:
// Continue on to checks below
break
}

let length1 = d1.count
if length1 != d2.count {
let length2 = d2.count

// Unequal length data can never be equal
guard length1 == length2 else {
return false
}

if length1 > 0 {
return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in
return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in
return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0
// If they have the same base address and same count, it is equal
let b1Address = b1.baseAddress!
let b2Address = b2.baseAddress!

guard b1Address != b2Address else {
return true
}

// Compare the contents
return memcmp(b1Address, b2Address, b2.count) == 0
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/FoundationEssentials/Locale/Locale+Language.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ extension Locale {
if let languageCode = languageCode {
result += languageCode._normalizedIdentifier
}
if let script = script {
if let script = script, !script.identifier.isEmpty {
result += "-"
result += script._normalizedIdentifier
}
if let region = region {
if let region = region, !region.identifier.isEmpty {
result += "_"
result += region._normalizedIdentifier
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,11 @@ extension Locale.Language {
public var minimalIdentifier : String {
let componentsIdentifier = components.identifier

guard !componentsIdentifier.isEmpty else {
// Just return "". Nothing to reduce.
return componentsIdentifier
}

let localeIDWithLikelySubtags = _withFixedCharBuffer { buffer, size, status in
return uloc_minimizeSubtags(componentsIdentifier, buffer, size, &status)
}
Expand All @@ -543,6 +548,11 @@ extension Locale.Language {
/// Returns a BCP-47 identifier that always includes the script: "zh-Hant-TW", "en-Latn-US"
public var maximalIdentifier : String {
let id = components.identifier
guard !id.isEmpty else {
// Just return "" instead of trying to fill it up
return id
}

let localeIDWithLikelySubtags = _withFixedCharBuffer { buffer, size, status in
return uloc_addLikelySubtags(id, buffer, size, &status)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1209,8 +1209,8 @@ internal final class _LocaleICU: _LocaleProtocol, Sendable {
}
}

// Check prefs
if let firstWeekdayPref = prefs?.firstWeekday {
// Check prefs. The value doesn't matter here - we check it again in the `forceFirstWeekday` function, and it is immutable.
if prefs?.firstWeekday != nil {
let calendarId = calendarIdentifier
if let first = forceFirstWeekday(calendarId) {
state.firstDayOfWeek = first
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,10 @@ internal class _NSSwiftLocale: _NSLocaleBridge, @unchecked Sendable {
switch locale.temperatureUnit {
case .celsius: return NSLocaleTemperatureUnitCelsius
case .fahrenheit: return NSLocaleTemperatureUnitFahrenheit
#if !FOUNDATION_FRAMEWORK
// On non-framework builds, the enum is non-closed and `package` visibility, so we need a default
default: return NSLocaleTemperatureUnitCelsius
#endif
}
case .decimalSeparator: return self.decimalSeparator
case .groupingSeparator: return self.groupingSeparator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,12 @@ internal final class _TimeZoneICU: _TimeZoneProtocol, Sendable {
return Self.timeZoneDisplayName(for: c, timeZoneName: identifier, localeName: locID, isShort: false, isGeneric: true, isDaylight: false)
case .shortGeneric:
return Self.timeZoneDisplayName(for: c, timeZoneName: identifier, localeName: locID, isShort: true, isGeneric: true, isDaylight: false)
#if FOUNDATION_FRAMEWORK
// We only need this when building in ObjC mode, when the enum comes from a .h
@unknown default:
// Use standard style
return Self.timeZoneDisplayName(for: c, timeZoneName: identifier, localeName: locID, isShort: false, isGeneric: false, isDaylight: false)
#endif
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ final class AttributedStringIndexValidityTests: XCTestCase {
}

public func testMutationInvalidation() {
func checkInPlace(_ mutation: (inout AttributedString) -> (), file: StaticString = #file, line: UInt = #line) {
func checkInPlace(_ mutation: (inout AttributedString) -> (), file: StaticString = #filePath, line: UInt = #line) {
var str = AttributedString("Hello World")
let idxA = str.startIndex
let idxB = str.index(afterCharacter: idxA)
Expand All @@ -158,7 +158,7 @@ final class AttributedStringIndexValidityTests: XCTestCase {
XCTAssertFalse(RangeSet(idxA ..< idxB).isValid(within: str), "Initial range set was valid in in-place mutated", file: file, line: line)
}

func checkCopy(_ mutation: (inout AttributedString) -> (), file: StaticString = #file, line: UInt = #line) {
func checkCopy(_ mutation: (inout AttributedString) -> (), file: StaticString = #filePath, line: UInt = #line) {
let str = AttributedString("Hello World")
let idxA = str.startIndex
let idxB = str.index(afterCharacter: idxA)
Expand All @@ -185,7 +185,7 @@ final class AttributedStringIndexValidityTests: XCTestCase {
XCTAssertFalse(RangeSet(idxA ..< idxB).isValid(within: copy), "Initial range set was valid in copy", file: file, line: line)
}

func check(_ mutation: (inout AttributedString) -> (), file: StaticString = #file, line: UInt = #line) {
func check(_ mutation: (inout AttributedString) -> (), file: StaticString = #filePath, line: UInt = #line) {
checkInPlace(mutation, file: file, line: line)
checkCopy(mutation, file: file, line: line)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1882,7 +1882,7 @@ E {
func check<T: Equatable>(
_ a: some Sequence<T>,
_ b: some Sequence<T>,
file: StaticString = #file, line: UInt = #line
file: StaticString = #filePath, line: UInt = #line
) {
XCTAssertTrue(
a.elementsEqual(b),
Expand Down
1 change: 1 addition & 0 deletions Tests/FoundationEssentialsTests/DataIOTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ class DataIOTests : XCTestCase {

#if FOUNDATION_FRAMEWORK
// String(contentsOf:) is not available outside the framework yet
@available(*, deprecated)
func test_emptyFileString() {
let data = Data()
let url = testURL()
Expand Down
2 changes: 1 addition & 1 deletion Tests/FoundationEssentialsTests/StringTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1319,7 +1319,7 @@ final class StringTests : XCTestCase {

}

func verifyEncoding(_ encoding: String._Encoding, valid: [String], invalid: [String], file: StaticString = #file, line: UInt = #line) throws {
func verifyEncoding(_ encoding: String._Encoding, valid: [String], invalid: [String], file: StaticString = #filePath, line: UInt = #line) throws {
for string in valid {
let data = try XCTUnwrap(string.data(using: encoding), "Failed to encode \(string.debugDescription)", file: file, line: line)
XCTAssertNotNil(String(data: data, encoding: encoding), "Failed to decode \(data) (\(string.debugDescription))", file: file, line: line)
Expand Down
Loading