├── .editorconfig
├── NonEmpty.playground
├── Contents.swift
└── contents.xcplayground
├── .swiftpm
└── xcode
│ └── package.xcworkspace
│ └── contents.xcworkspacedata
├── Package.swift
├── Makefile
├── Sources
└── NonEmpty
│ ├── NonEmpty+ExpressibleByArrayLiteral.swift
│ ├── NonEmpty+ExpressibleByDictionaryLiteral.swift
│ ├── NonEmpty+RangeReplaceableCollection.swift
│ ├── NonEmpty+Dictionary.swift
│ ├── NonEmpty+String.swift
│ ├── NonEmpty+SetAlgebra.swift
│ └── NonEmpty.swift
├── .github
├── workflows
│ ├── format.yml
│ └── ci.yml
└── CODE_OF_CONDUCT.md
├── LICENSE
├── .gitignore
├── README.md
└── Tests
└── NonEmptyTests
└── NonEmptyTests.swift
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | indent_style = space
7 | indent_size = 2
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 |
--------------------------------------------------------------------------------
/NonEmpty.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import NonEmpty
2 |
3 | let xs = NonEmptyArray(42, 1, 3, 2)
4 |
5 | let str: NonEmptyString = xs
6 | .sorted()
7 | .map { NonEmptyString($0)! }
8 | .joined(separator: ",")
9 |
--------------------------------------------------------------------------------
/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/NonEmpty.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version:5.1
2 | import PackageDescription
3 |
4 | let package = Package(
5 | name: "swift-nonempty",
6 | products: [
7 | .library(name: "NonEmpty", targets: ["NonEmpty"])
8 | ],
9 | targets: [
10 | .target(name: "NonEmpty", dependencies: []),
11 | .testTarget(name: "NonEmptyTests", dependencies: ["NonEmpty"]),
12 | ]
13 | )
14 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | default: test-all
2 |
3 | test-all: test-linux test-swift
4 |
5 | test-linux:
6 | docker run \
7 | --rm \
8 | -v "$(PWD):$(PWD)" \
9 | -w "$(PWD)" \
10 | swift:5.3 \
11 | bash -c 'make test-swift'
12 |
13 | test-swift:
14 | swift test \
15 | --enable-test-discovery \
16 | --parallel
17 |
18 | format:
19 | swift format --in-place --recursive ./Package.swift ./Sources ./Tests
20 |
21 | .PHONY: format test-all test-swift test-workspace
22 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | extension NonEmpty: ExpressibleByArrayLiteral where Collection: ExpressibleByArrayLiteral {
2 | public init(arrayLiteral elements: Element...) {
3 | precondition(!elements.isEmpty, "Can't construct \(Self.self) from empty array literal")
4 | let f = unsafeBitCast(
5 | Collection.init(arrayLiteral:),
6 | to: (([Element]) -> Collection).self
7 | )
8 | self.init(rawValue: f(elements))!
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+ExpressibleByDictionaryLiteral.swift:
--------------------------------------------------------------------------------
1 | extension NonEmpty: ExpressibleByDictionaryLiteral
2 | where Collection: ExpressibleByDictionaryLiteral {
3 | public init(dictionaryLiteral elements: (Collection.Key, Collection.Value)...) {
4 | precondition(!elements.isEmpty, "Can't construct \(Self.self) from empty dictionary literal")
5 | let f = unsafeBitCast(
6 | Collection.init(dictionaryLiteral:),
7 | to: (([(Collection.Key, Collection.Value)]) -> Collection).self
8 | )
9 | self.init(rawValue: f(elements))!
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/.github/workflows/format.yml:
--------------------------------------------------------------------------------
1 | name: Format
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | swift_format:
10 | name: swift-format
11 | runs-on: macOS-11
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Xcode Select
15 | run: sudo xcode-select -s /Applications/Xcode_13.0.app
16 | - name: Tap
17 | run: brew tap pointfreeco/formulae
18 | - name: Install
19 | run: brew install Formulae/swift-format@5.5
20 | - name: Format
21 | run: make format
22 | - uses: stefanzweifel/git-auto-commit-action@v4
23 | with:
24 | commit_message: Run swift-format
25 | branch: 'main'
26 | env:
27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
28 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - '*'
10 |
11 | jobs:
12 | macos:
13 | name: macOS
14 | runs-on: macOS-latest
15 | strategy:
16 | matrix:
17 | xcode:
18 | - '11.7'
19 | - '12.4'
20 | - '12.5.1'
21 | - '13.0'
22 | steps:
23 | - uses: actions/checkout@v2
24 | - name: Select Xcode ${{ matrix.xcode }}
25 | run: sudo xcode-select -s /Applications/Xcode_${{ matrix.xcode }}.app
26 | - name: Run tests
27 | run: make test-swift
28 | - name: Build release
29 | run: swift build -c release
30 |
31 | linux:
32 | name: Linux
33 | runs-on: ubuntu-latest
34 | steps:
35 | - uses: actions/checkout@v2
36 | - name: Run tests
37 | run: make test-linux
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Point-Free, Inc.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
4 |
5 | ## Build generated
6 | build/
7 | DerivedData/
8 |
9 | ## Various settings
10 | *.pbxuser
11 | !default.pbxuser
12 | *.mode1v3
13 | !default.mode1v3
14 | *.mode2v3
15 | !default.mode2v3
16 | *.perspectivev3
17 | !default.perspectivev3
18 | xcuserdata/
19 |
20 | ## Other
21 | *.moved-aside
22 | *.xccheckout
23 | *.xcscmblueprint
24 |
25 | ## Obj-C/Swift specific
26 | *.hmap
27 | *.ipa
28 | *.dSYM.zip
29 | *.dSYM
30 |
31 | ## Playgrounds
32 | timeline.xctimeline
33 | playground.xcworkspace
34 |
35 | # Swift Package Manager
36 | #
37 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
38 | # Packages/
39 | # Package.pins
40 | .build/
41 |
42 | # CocoaPods
43 | #
44 | # We recommend against adding the Pods directory to your .gitignore. However
45 | # you should judge for yourself, the pros and cons are mentioned at:
46 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
47 | #
48 | # Pods/
49 |
50 | # Carthage
51 | #
52 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
53 | # Carthage/Checkouts
54 |
55 | Carthage/Build
56 |
57 | # fastlane
58 | #
59 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
60 | # screenshots whenever they are needed.
61 | # For more information about the recommended setup visit:
62 | # https://docs.fastlane.tools/best-practices/source-control/#source-control
63 |
64 | fastlane/report.xml
65 | fastlane/Preview.html
66 | fastlane/screenshots
67 | fastlane/test_output
68 |
69 | .DS_Store
70 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+RangeReplaceableCollection.swift:
--------------------------------------------------------------------------------
1 | // NB: `NonEmpty` does not conditionally conform to `RangeReplaceableCollection` because it contains destructive methods.
2 | extension NonEmpty where Collection: RangeReplaceableCollection {
3 | public init(_ head: Element, _ tail: Element...) {
4 | var tail = tail
5 | tail.insert(head, at: tail.startIndex)
6 | self.init(rawValue: Collection(tail))!
7 | }
8 |
9 | public init?(_ elements: S) where S: Sequence, Collection.Element == S.Element {
10 | self.init(rawValue: Collection(elements))
11 | }
12 |
13 | public mutating func append(_ newElement: Element) {
14 | self.rawValue.append(newElement)
15 | }
16 |
17 | public mutating func append(contentsOf newElements: S) where Element == S.Element {
18 | self.rawValue.append(contentsOf: newElements)
19 | }
20 |
21 | public mutating func insert(_ newElement: Element, at i: Index) {
22 | self.rawValue.insert(newElement, at: i)
23 | }
24 |
25 | public mutating func insert(
26 | contentsOf newElements: S, at i: Index
27 | ) where S: Swift.Collection, Element == S.Element {
28 | self.rawValue.insert(contentsOf: newElements, at: i)
29 | }
30 |
31 | public static func += (lhs: inout Self, rhs: S) where Element == S.Element {
32 | lhs.append(contentsOf: rhs)
33 | }
34 |
35 | public static func + (lhs: Self, rhs: Self) -> Self {
36 | var lhs = lhs
37 | lhs += rhs
38 | return lhs
39 | }
40 |
41 | public static func + (lhs: Self, rhs: S) -> Self where Element == S.Element {
42 | var lhs = lhs
43 | lhs += rhs
44 | return lhs
45 | }
46 |
47 | public static func + (lhs: S, rhs: Self) -> Self where Element == S.Element {
48 | var rhs = rhs
49 | rhs.insert(contentsOf: ContiguousArray(lhs), at: rhs.startIndex)
50 | return rhs
51 | }
52 | }
53 |
54 | extension NonEmpty {
55 | public func joined(
56 | separator: S
57 | )
58 | -> NonEmpty
59 | where Element == NonEmpty, S.Element == C.Element {
60 | NonEmpty(rawValue: C(self.rawValue.joined(separator: separator)))!
61 | }
62 |
63 | public func joined() -> NonEmpty
64 | where Element == NonEmpty {
65 | return joined(separator: C())
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+Dictionary.swift:
--------------------------------------------------------------------------------
1 | public typealias NonEmptyDictionary = NonEmpty<[Key: Value]> where Key: Hashable
2 |
3 | public protocol _DictionaryProtocol: Collection where Element == (key: Key, value: Value) {
4 | associatedtype Key: Hashable
5 | associatedtype Value
6 | var keys: Dictionary.Keys { get }
7 | subscript(key: Key) -> Value? { get set }
8 | mutating func merge(
9 | _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value
10 | ) rethrows where S.Element == (Key, Value)
11 | mutating func merge(
12 | _ other: [Key: Value], uniquingKeysWith combine: (Value, Value) throws -> Value
13 | ) rethrows
14 | @discardableResult mutating func removeValue(forKey key: Key) -> Value?
15 | @discardableResult mutating func updateValue(_ value: Value, forKey key: Key) -> Value?
16 | }
17 |
18 | extension Dictionary: _DictionaryProtocol {}
19 |
20 | extension NonEmpty where Collection: _DictionaryProtocol {
21 | public init(_ head: Element, _ tail: Collection) {
22 | guard !tail.keys.contains(head.key) else { fatalError("Dictionary contains duplicate key") }
23 | var tail = tail
24 | tail[head.key] = head.value
25 | self.init(rawValue: tail)!
26 | }
27 |
28 | public init(
29 | _ head: Element,
30 | _ tail: Collection,
31 | uniquingKeysWith combine: (Collection.Value, Collection.Value) throws -> Collection.Value
32 | ) rethrows {
33 |
34 | var tail = tail
35 | if let otherValue = tail.removeValue(forKey: head.0) {
36 | tail[head.key] = try combine(head.value, otherValue)
37 | } else {
38 | tail[head.key] = head.value
39 | }
40 | self.init(rawValue: tail)!
41 | }
42 |
43 | public subscript(key: Collection.Key) -> Collection.Value? {
44 | self.rawValue[key]
45 | }
46 |
47 | public mutating func merge(
48 | _ other: S,
49 | uniquingKeysWith combine: (Collection.Value, Collection.Value) throws -> Collection.Value
50 | ) rethrows where S.Element == (Collection.Key, Collection.Value) {
51 |
52 | try self.rawValue.merge(other, uniquingKeysWith: combine)
53 | }
54 |
55 | public func merging(
56 | _ other: S,
57 | uniquingKeysWith combine: (Collection.Value, Collection.Value) throws -> Collection.Value
58 | ) rethrows -> NonEmpty where S.Element == (Collection.Key, Collection.Value) {
59 |
60 | var copy = self
61 | try copy.merge(other, uniquingKeysWith: combine)
62 | return copy
63 | }
64 |
65 | public mutating func merge(
66 | _ other: [Collection.Key: Collection.Value],
67 | uniquingKeysWith combine: (Collection.Value, Collection.Value) throws -> Collection.Value
68 | ) rethrows {
69 |
70 | try self.rawValue.merge(other, uniquingKeysWith: combine)
71 | }
72 |
73 | public func merging(
74 | _ other: [Collection.Key: Collection.Value],
75 | uniquingKeysWith combine: (Collection.Value, Collection.Value) throws -> Collection.Value
76 | ) rethrows -> NonEmpty {
77 |
78 | var copy = self
79 | try copy.merge(other, uniquingKeysWith: combine)
80 | return copy
81 | }
82 |
83 | @discardableResult
84 | public mutating func updateValue(_ value: Collection.Value, forKey key: Collection.Key)
85 | -> Collection.Value?
86 | {
87 | self.rawValue.updateValue(value, forKey: key)
88 | }
89 | }
90 |
91 | extension NonEmpty where Collection: _DictionaryProtocol, Collection.Value: Equatable {
92 | public static func == (lhs: NonEmpty, rhs: NonEmpty) -> Bool {
93 | return Dictionary(uniqueKeysWithValues: Array(lhs))
94 | == Dictionary(uniqueKeysWithValues: Array(rhs))
95 | }
96 | }
97 |
98 | extension NonEmpty where Collection: _DictionaryProtocol & ExpressibleByDictionaryLiteral {
99 | public init(_ head: Element) {
100 | self.init(rawValue: [head.key: head.value])!
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+String.swift:
--------------------------------------------------------------------------------
1 | public typealias NonEmptyString = NonEmpty
2 |
3 | extension NonEmptyString {
4 | @_disfavoredOverload
5 | public init?(_ value: T) where T: LosslessStringConvertible {
6 | self.init(String(value))
7 | }
8 | }
9 |
10 | extension NonEmpty: ExpressibleByUnicodeScalarLiteral
11 | where Collection: ExpressibleByUnicodeScalarLiteral {
12 | public typealias UnicodeScalarLiteralType = Collection.UnicodeScalarLiteralType
13 |
14 | public init(unicodeScalarLiteral value: Collection.UnicodeScalarLiteralType) {
15 | self.init(rawValue: Collection(unicodeScalarLiteral: value))!
16 | }
17 | }
18 |
19 | extension NonEmpty: ExpressibleByExtendedGraphemeClusterLiteral
20 | where Collection: ExpressibleByExtendedGraphemeClusterLiteral {
21 | public typealias ExtendedGraphemeClusterLiteralType = Collection
22 | .ExtendedGraphemeClusterLiteralType
23 |
24 | public init(extendedGraphemeClusterLiteral value: Collection.ExtendedGraphemeClusterLiteralType) {
25 | self.init(rawValue: Collection(extendedGraphemeClusterLiteral: value))!
26 | }
27 | }
28 |
29 | extension NonEmpty: ExpressibleByStringLiteral where Collection: ExpressibleByStringLiteral {
30 | public typealias StringLiteralType = Collection.StringLiteralType
31 |
32 | public init(stringLiteral value: Collection.StringLiteralType) {
33 | self.init(rawValue: Collection(stringLiteral: value))!
34 | }
35 | }
36 |
37 | extension NonEmpty: TextOutputStreamable where Collection: TextOutputStreamable {
38 | public func write(to target: inout Target) where Target: TextOutputStream {
39 | self.rawValue.write(to: &target)
40 | }
41 | }
42 |
43 | extension NonEmpty: TextOutputStream where Collection: TextOutputStream {
44 | public mutating func write(_ string: String) {
45 | self.rawValue.write(string)
46 | }
47 | }
48 |
49 | extension NonEmpty: LosslessStringConvertible where Collection: LosslessStringConvertible {
50 | public init?(_ description: String) {
51 | guard let string = Collection(description) else { return nil }
52 | self.init(rawValue: string)
53 | }
54 | }
55 |
56 | extension NonEmpty: ExpressibleByStringInterpolation
57 | where
58 | Collection: ExpressibleByStringInterpolation,
59 | Collection.StringLiteralType == DefaultStringInterpolation.StringLiteralType
60 | {}
61 |
62 | extension NonEmpty where Collection: StringProtocol {
63 | public typealias UTF8View = Collection.UTF8View
64 | public typealias UTF16View = Collection.UTF16View
65 | public typealias UnicodeScalarView = Collection.UnicodeScalarView
66 |
67 | public var utf8: UTF8View { self.rawValue.utf8 }
68 | public var utf16: UTF16View { self.rawValue.utf16 }
69 | public var unicodeScalars: UnicodeScalarView { self.rawValue.unicodeScalars }
70 |
71 | public init(
72 | decoding codeUnits: C, as sourceEncoding: Encoding.Type
73 | ) where C: Swift.Collection, Encoding: _UnicodeEncoding, C.Element == Encoding.CodeUnit {
74 | self.init(rawValue: Collection(decoding: codeUnits, as: sourceEncoding))!
75 | }
76 |
77 | public init(cString nullTerminatedUTF8: UnsafePointer) {
78 | self.init(rawValue: Collection(cString: nullTerminatedUTF8))!
79 | }
80 |
81 | public init(
82 | decodingCString nullTerminatedCodeUnits: UnsafePointer,
83 | as sourceEncoding: Encoding.Type
84 | ) where Encoding: _UnicodeEncoding {
85 | self.init(rawValue: Collection(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding))!
86 | }
87 |
88 | public func withCString(_ body: (UnsafePointer) throws -> Result) rethrows
89 | -> Result
90 | {
91 | try self.rawValue.withCString(body)
92 | }
93 |
94 | public func withCString(
95 | encodedAs targetEncoding: Encoding.Type,
96 | _ body: (UnsafePointer) throws -> Result
97 | ) rethrows -> Result where Encoding: _UnicodeEncoding {
98 | try self.rawValue.withCString(encodedAs: targetEncoding, body)
99 | }
100 |
101 | public func lowercased() -> NonEmptyString {
102 | NonEmptyString(self.rawValue.lowercased())!
103 | }
104 |
105 | public func uppercased() -> NonEmptyString {
106 | NonEmptyString(self.rawValue.uppercased())!
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty+SetAlgebra.swift:
--------------------------------------------------------------------------------
1 | public typealias NonEmptySet = NonEmpty> where Element: Hashable
2 |
3 | // NB: `NonEmpty` does not conditionally conform to `SetAlgebra` because it contains destructive methods.
4 | extension NonEmpty where Collection: SetAlgebra, Collection.Element: Hashable {
5 | public init(_ head: Collection.Element, _ tail: Collection.Element...) {
6 | var tail = Collection(tail)
7 | tail.insert(head)
8 | self.init(rawValue: tail)!
9 | }
10 |
11 | public init?(_ elements: S) where S: Sequence, Collection.Element == S.Element {
12 | self.init(rawValue: Collection(elements))
13 | }
14 |
15 | public func contains(_ member: Collection.Element) -> Bool {
16 | self.rawValue.contains(member)
17 | }
18 |
19 | @_disfavoredOverload
20 | public func union(_ other: NonEmpty) -> NonEmpty {
21 | var copy = self
22 | copy.formUnion(other)
23 | return copy
24 | }
25 |
26 | public func union(_ other: Collection) -> NonEmpty {
27 | var copy = self
28 | copy.formUnion(other)
29 | return copy
30 | }
31 |
32 | @_disfavoredOverload
33 | public func intersection(_ other: NonEmpty) -> Collection {
34 | self.rawValue.intersection(other.rawValue)
35 | }
36 |
37 | public func intersection(_ other: Collection) -> Collection {
38 | self.rawValue.intersection(other)
39 | }
40 |
41 | @_disfavoredOverload
42 | public func symmetricDifference(_ other: NonEmpty) -> Collection {
43 | self.rawValue.symmetricDifference(other.rawValue)
44 | }
45 |
46 | public func symmetricDifference(_ other: Collection) -> Collection {
47 | self.rawValue.symmetricDifference(other)
48 | }
49 |
50 | @discardableResult
51 | public mutating func insert(_ newMember: Collection.Element) -> (
52 | inserted: Bool, memberAfterInsert: Collection.Element
53 | ) {
54 | self.rawValue.insert(newMember)
55 | }
56 |
57 | @discardableResult
58 | public mutating func update(with newMember: Collection.Element) -> Collection.Element? {
59 | self.rawValue.update(with: newMember)
60 | }
61 |
62 | @_disfavoredOverload
63 | public mutating func formUnion(_ other: NonEmpty) {
64 | self.rawValue.formUnion(other.rawValue)
65 | }
66 |
67 | public mutating func formUnion(_ other: Collection) {
68 | self.rawValue.formUnion(other)
69 | }
70 |
71 | @_disfavoredOverload
72 | public func subtracting(_ other: NonEmpty) -> Collection {
73 | self.rawValue.subtracting(other.rawValue)
74 | }
75 |
76 | public func subtracting(_ other: Collection) -> Collection {
77 | self.rawValue.subtracting(other)
78 | }
79 |
80 | @_disfavoredOverload
81 | public func isDisjoint(with other: NonEmpty) -> Bool {
82 | self.rawValue.isDisjoint(with: other.rawValue)
83 | }
84 |
85 | public func isDisjoint(with other: Collection) -> Bool {
86 | self.rawValue.isDisjoint(with: other)
87 | }
88 |
89 | @_disfavoredOverload
90 | public func isSubset(of other: NonEmpty) -> Bool {
91 | self.rawValue.isSubset(of: other.rawValue)
92 | }
93 |
94 | public func isSubset(of other: Collection) -> Bool {
95 | self.rawValue.isSubset(of: other)
96 | }
97 |
98 | @_disfavoredOverload
99 | public func isSuperset(of other: NonEmpty) -> Bool {
100 | self.rawValue.isSuperset(of: other.rawValue)
101 | }
102 |
103 | public func isSuperset(of other: Collection) -> Bool {
104 | self.rawValue.isSuperset(of: other)
105 | }
106 |
107 | @_disfavoredOverload
108 | public func isStrictSubset(of other: NonEmpty) -> Bool {
109 | self.rawValue.isStrictSubset(of: other.rawValue)
110 | }
111 |
112 | public func isStrictSubset(of other: Collection) -> Bool {
113 | self.rawValue.isStrictSubset(of: other)
114 | }
115 |
116 | @_disfavoredOverload
117 | public func isStrictSuperset(of other: NonEmpty) -> Bool {
118 | self.rawValue.isStrictSuperset(of: other.rawValue)
119 | }
120 |
121 | public func isStrictSuperset(of other: Collection) -> Bool {
122 | self.rawValue.isStrictSuperset(of: other)
123 | }
124 | }
125 |
126 | extension SetAlgebra where Self: Collection, Element: Hashable {
127 | public func union(_ other: NonEmpty) -> NonEmpty {
128 | var copy = other
129 | copy.formUnion(self)
130 | return copy
131 | }
132 |
133 | public func intersection(_ other: NonEmpty) -> Self {
134 | self.intersection(other.rawValue)
135 | }
136 |
137 | public func symmetricDifference(_ other: NonEmpty) -> Self {
138 | self.symmetricDifference(other.rawValue)
139 | }
140 |
141 | public mutating func formUnion(_ other: NonEmpty) {
142 | self.formUnion(other.rawValue)
143 | }
144 |
145 | public func subtracting(_ other: NonEmpty) -> Self {
146 | self.subtracting(other.rawValue)
147 | }
148 |
149 | public func isDisjoint(with other: NonEmpty) -> Bool {
150 | self.isDisjoint(with: other.rawValue)
151 | }
152 |
153 | public func isSubset(of other: NonEmpty) -> Bool {
154 | self.isSubset(of: other.rawValue)
155 | }
156 |
157 | public func isSuperset(of other: NonEmpty) -> Bool {
158 | self.isSuperset(of: other.rawValue)
159 | }
160 |
161 | public func isStrictSubset(of other: NonEmpty) -> Bool {
162 | self.isStrictSubset(of: other.rawValue)
163 | }
164 |
165 | public func isStrictSuperset(of other: NonEmpty) -> Bool {
166 | self.isStrictSuperset(of: other.rawValue)
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/Sources/NonEmpty/NonEmpty.swift:
--------------------------------------------------------------------------------
1 | @dynamicMemberLookup
2 | public struct NonEmpty: Swift.Collection {
3 | public typealias Element = Collection.Element
4 | public typealias Index = Collection.Index
5 |
6 | public internal(set) var rawValue: Collection
7 |
8 | public init?(rawValue: Collection) {
9 | guard !rawValue.isEmpty else { return nil }
10 | self.rawValue = rawValue
11 | }
12 |
13 | public subscript(dynamicMember keyPath: KeyPath) -> Subject {
14 | self.rawValue[keyPath: keyPath]
15 | }
16 |
17 | public var startIndex: Index { self.rawValue.startIndex }
18 |
19 | public var endIndex: Index { self.rawValue.endIndex }
20 |
21 | public subscript(position: Index) -> Element { self.rawValue[position] }
22 |
23 | public func index(after i: Index) -> Index {
24 | self.rawValue.index(after: i)
25 | }
26 |
27 | public var first: Element { self.rawValue.first! }
28 |
29 | public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element {
30 | try self.rawValue.max(by: areInIncreasingOrder)!
31 | }
32 |
33 | public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element {
34 | try self.rawValue.min(by: areInIncreasingOrder)!
35 | }
36 |
37 | public func sorted(
38 | by areInIncreasingOrder: (Element, Element) throws -> Bool
39 | ) rethrows -> NonEmpty<[Element]> {
40 | NonEmpty<[Element]>(rawValue: try self.rawValue.sorted(by: areInIncreasingOrder))!
41 | }
42 |
43 | public func randomElement(using generator: inout T) -> Element where T: RandomNumberGenerator {
44 | self.rawValue.randomElement(using: &generator)!
45 | }
46 |
47 | public func randomElement() -> Element {
48 | self.rawValue.randomElement()!
49 | }
50 |
51 | public func shuffled(using generator: inout T) -> NonEmpty<[Element]>
52 | where T: RandomNumberGenerator {
53 | NonEmpty<[Element]>(rawValue: self.rawValue.shuffled(using: &generator))!
54 | }
55 |
56 | public func shuffled() -> NonEmpty<[Element]> {
57 | NonEmpty<[Element]>(rawValue: self.rawValue.shuffled())!
58 | }
59 |
60 | public func map(_ transform: (Element) throws -> T) rethrows -> NonEmpty<[T]> {
61 | NonEmpty<[T]>(rawValue: try self.rawValue.map(transform))!
62 | }
63 |
64 | public func flatMap(
65 | _ transform: (Element) throws -> NonEmpty
66 | ) rethrows -> NonEmpty<[SegmentOfResult.Element]> where SegmentOfResult: Sequence {
67 | NonEmpty<[SegmentOfResult.Element]>(rawValue: try self.rawValue.flatMap(transform))!
68 | }
69 | }
70 |
71 | extension NonEmpty: CustomStringConvertible {
72 | public var description: String {
73 | return String(describing: self.rawValue)
74 | }
75 | }
76 |
77 | extension NonEmpty: Equatable where Collection: Equatable {}
78 |
79 | extension NonEmpty: Hashable where Collection: Hashable {}
80 |
81 | extension NonEmpty: Comparable where Collection: Comparable {
82 | public static func < (lhs: Self, rhs: Self) -> Bool {
83 | lhs.rawValue < rhs.rawValue
84 | }
85 | }
86 |
87 | #if canImport(_Concurrency) && compiler(>=5.5)
88 | extension NonEmpty: Sendable where Collection: Sendable {}
89 | #endif
90 |
91 | extension NonEmpty: Encodable where Collection: Encodable {
92 | public func encode(to encoder: Encoder) throws {
93 | do {
94 | var container = encoder.singleValueContainer()
95 | try container.encode(self.rawValue)
96 | } catch {
97 | try self.rawValue.encode(to: encoder)
98 | }
99 | }
100 | }
101 |
102 | extension NonEmpty: Decodable where Collection: Decodable {
103 | public init(from decoder: Decoder) throws {
104 | let collection: Collection
105 | do {
106 | collection = try decoder.singleValueContainer().decode(Collection.self)
107 | } catch {
108 | collection = try Collection(from: decoder)
109 | }
110 |
111 | guard !collection.isEmpty else {
112 | throw DecodingError.dataCorrupted(
113 | .init(codingPath: decoder.codingPath, debugDescription: "Non-empty collection expected")
114 | )
115 | }
116 | self.init(rawValue: collection)!
117 | }
118 | }
119 |
120 | extension NonEmpty: RawRepresentable {}
121 |
122 | extension NonEmpty where Collection.Element: Comparable {
123 | public func max() -> Element {
124 | self.rawValue.max()!
125 | }
126 |
127 | public func min() -> Element {
128 | self.rawValue.min()!
129 | }
130 |
131 | public func sorted() -> NonEmpty<[Element]> {
132 | return NonEmpty<[Element]>(rawValue: self.rawValue.sorted())!
133 | }
134 | }
135 |
136 | extension NonEmpty: BidirectionalCollection where Collection: BidirectionalCollection {
137 | public func index(before i: Index) -> Index {
138 | self.rawValue.index(before: i)
139 | }
140 |
141 | public var last: Element { self.rawValue.last! }
142 | }
143 |
144 | extension NonEmpty: MutableCollection where Collection: MutableCollection {
145 | public subscript(position: Index) -> Element {
146 | _read { yield self.rawValue[position] }
147 | _modify { yield &self.rawValue[position] }
148 | }
149 | }
150 |
151 | extension NonEmpty: RandomAccessCollection where Collection: RandomAccessCollection {}
152 |
153 | extension NonEmpty where Collection: MutableCollection & RandomAccessCollection {
154 | public mutating func shuffle(using generator: inout T) {
155 | self.rawValue.shuffle(using: &generator)
156 | }
157 | }
158 |
159 | public typealias NonEmptyArray = NonEmpty<[Element]>
160 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, caste, color, religion, or sexual
10 | identity and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the overall
26 | community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or advances of
31 | any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email address,
35 | without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | .
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series of
86 | actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or permanent
93 | ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within the
113 | community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.1, available at
119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120 |
121 | Community Impact Guidelines were inspired by
122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123 |
124 | For answers to common questions about this code of conduct, see the FAQ at
125 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126 | [https://www.contributor-covenant.org/translations][translations].
127 |
128 | [homepage]: https://www.contributor-covenant.org
129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130 | [Mozilla CoC]: https://github.com/mozilla/diversity
131 | [FAQ]: https://www.contributor-covenant.org/faq
132 | [translations]: https://www.contributor-covenant.org/translations
133 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🎁 NonEmpty
2 |
3 | [](https://actions-badge.atrox.dev/pointfreeco/swift-nonempty/goto)
4 | [](https://swiftpackageindex.com/pointfreeco/swift-nonempty)
5 | [](https://swiftpackageindex.com/pointfreeco/swift-nonempty)
6 |
7 | A compile-time guarantee that a collection contains a value.
8 |
9 | ## Motivation
10 |
11 | We often work with collections that should _never_ be empty, but the type system makes no such guarantees, so we're forced to handle that empty case, often with `if` and `guard` statements. `NonEmpty` is a lightweight type that can transform _any_ collection type into a non-empty version. Some examples:
12 |
13 | ```swift
14 | // 1.) A non-empty array of integers
15 | let xs = NonEmpty<[Int]>(1, 2, 3, 4)
16 | xs.first + 1 // `first` is non-optional since it's guaranteed to be present
17 |
18 | // 2.) A non-empty set of integers
19 | let ys = NonEmpty>(1, 1, 2, 2, 3, 4)
20 | ys.forEach { print($0) } // => 1, 2, 3, 4
21 |
22 | // 3.) A non-empty dictionary of values
23 | let zs = NonEmpty<[Int: String]>((1, "one"), [2: "two", 3: "three"])
24 |
25 | // 4.) A non-empty string
26 | let helloWorld = NonEmpty("H", "ello World")
27 | print("\(helloWorld)!") // "Hello World!"
28 | ```
29 |
30 | ## Applications
31 |
32 | There are many applications of non-empty collection types but it can be hard to see since the Swift standard library does not give us this type. Here are just a few such applications:
33 |
34 | ### Strengthen 1st party APIs
35 |
36 | Many APIs take and return empty-able arrays when they can in fact guarantee that the arrays are non-empty. Consider a `groupBy` function:
37 |
38 | ```swift
39 | extension Sequence {
40 | func groupBy(_ f: (Element) -> A) -> [A: [Element]] {
41 | // Unimplemented
42 | }
43 | }
44 |
45 | Array(1...10)
46 | .groupBy { $0 % 3 }
47 | // [0: [3, 6, 9], 1: [1, 4, 7, 10], 2: [2, 5, 8]]
48 | ```
49 |
50 | However, the array `[Element]` inside the return type `[A: [Element]]` can be guaranteed to never be empty, for the only way to produce an `A` is from an `Element`. Therefore the signature of this function could be strengthened to be:
51 |
52 | ```swift
53 | extension Sequence {
54 | func groupBy(_ f: (Element) -> A) -> [A: NonEmpty<[Element]>] {
55 | // Unimplemented
56 | }
57 | }
58 | ```
59 |
60 | ### Better interface with 3rd party APIs
61 |
62 | Sometimes a 3rd party API we interact with requires non-empty collections of values, and so in our code we should use non-empty types so that we can be sure to never send an empty values to the API. A good example of this is [GraphQL](https://graphql.org/). Here is a very simple query builder and printer:
63 |
64 | ```swift
65 | enum UserField: String { case id, name, email }
66 |
67 | func query(_ fields: Set) -> String {
68 | return (["{"] + fields.map { " \($0.rawValue)" } + ["}"])
69 | .joined()
70 | }
71 |
72 | print(query([.name, .email]))
73 | // {
74 | // name
75 | // email
76 | // }
77 |
78 | print(query([]))
79 | // {
80 | // }
81 | ```
82 |
83 | This last query is a programmer error, and will cause the GraphQL server to send back an error because it is not valid to send an empty query. We can prevent this from ever happening by instead forcing our query builder to work with non-empty sets:
84 |
85 | ```swift
86 | func query(_ fields: NonEmptySet) -> String {
87 | return (["{"] + fields.map { " \($0.rawValue)" } + ["}"])
88 | .joined()
89 | }
90 |
91 | print(query(.init(.name, .email)))
92 | // {
93 | // name
94 | // email
95 | // }
96 |
97 | print(query(.init()))
98 | // 🛑 Does not compile
99 | ```
100 |
101 | ### More expressive data structures
102 |
103 | A popular type in the Swift community (and other languages), is the `Result` type. It allows you to express a value that can be successful or be a failure. There's a related type that is also handy, called the `Validated` type:
104 |
105 | ```swift
106 | enum Validated {
107 | case valid(Value)
108 | case invalid([Error])
109 | }
110 | ```
111 |
112 | A value of type `Validated` is either valid, and hence comes with a `Value`, or it is invalid, and comes with an array of errors that describe what all is wrong with the value. For example:
113 |
114 | ```swift
115 | let validatedPassword: Validated =
116 | .invalid(["Password is too short.", "Password must contain at least one number."])
117 | ```
118 |
119 | This is useful because it allows you to describe all of the things wrong with a value, not just one thing. However, it doesn't make a lot of sense if we use an empty array of the list of validation errors:
120 |
121 | ```swift
122 | let validatedPassword: Validated = .invalid([]) // ???
123 | ```
124 |
125 | Instead, we should strengthen the `Validated` type to use a non-empty array:
126 |
127 | ```swift
128 | enum Validated {
129 | case valid(Value)
130 | case invalid(NonEmptyArray)
131 | }
132 | ```
133 |
134 | And now this is a compiler error:
135 |
136 | ```swift
137 | let validatedPassword: Validated = .invalid(.init([])) // 🛑
138 | ```
139 |
140 | ## Installation
141 |
142 | If you want to use NonEmpty in a project that uses [SwiftPM](https://swift.org/package-manager/), it's as simple as adding a dependency to your `Package.swift`:
143 |
144 | ``` swift
145 | dependencies: [
146 | .package(url: "https://github.com/pointfreeco/swift-nonempty.git", from: "0.3.0")
147 | ]
148 | ```
149 |
150 | ## Interested in learning more?
151 |
152 | These concepts (and more) are explored thoroughly in [Point-Free](https://www.pointfree.co), a video series exploring functional programming and Swift hosted by [Brandon Williams](https://twitter.com/mbrandonw) and [Stephen Celis](https://twitter.com/stephencelis).
153 |
154 | NonEmpty was first explored in [Episode #20](https://www.pointfree.co/episodes/ep20-nonempty):
155 |
156 |
157 |
158 |
159 |
160 | ## License
161 |
162 | All modules are released under the MIT license. See [LICENSE](LICENSE) for details.
163 |
--------------------------------------------------------------------------------
/Tests/NonEmptyTests/NonEmptyTests.swift:
--------------------------------------------------------------------------------
1 | import XCTest
2 |
3 | @testable import NonEmpty
4 |
5 | #if canImport(SwiftUI)
6 | import SwiftUI
7 | #endif
8 |
9 | final class NonEmptyTests: XCTestCase {
10 | func testCollection() {
11 | let xs = NonEmptyArray(1, 2, 3)
12 |
13 | XCTAssertEqual(3, xs.count)
14 | XCTAssertEqual(2, xs.first + 1)
15 | XCTAssertEqual(
16 | xs,
17 | NonEmptyArray(NonEmptyArray(1), NonEmptyArray(2), NonEmptyArray(3)).flatMap { $0 }
18 | )
19 | XCTAssertEqual(
20 | NonEmptyArray("1", "2", "3"),
21 | xs.map(String.init)
22 | )
23 | XCTAssertEqual(4, xs.min(by: >) + 1)
24 | XCTAssertEqual(2, xs.max(by: >) + 1)
25 | XCTAssertEqual(NonEmptyArray(3, 2, 1), xs.sorted(by: >))
26 | XCTAssertEqual([1, 2, 3], Array(xs))
27 |
28 | XCTAssertEqual(NonEmptyArray(1, 2, 3, 1, 2, 3), xs + xs)
29 | }
30 |
31 | func testBidirectionalCollection() {
32 | XCTAssertEqual(4, NonEmptyArray(1, 2, 3).last + 1)
33 | XCTAssertEqual(4, NonEmptyArray(3).last + 1)
34 | }
35 |
36 | func testMutableCollection() {
37 | var xs = NonEmptyArray(1, 2, 3)
38 | xs[0] = 42
39 | xs[1] = 43
40 | XCTAssertEqual(42, xs[0])
41 | XCTAssertEqual(43, xs[1])
42 | }
43 |
44 | func testRangeSubscript() {
45 | let xs = NonEmptyArray(1, 2, 3, 4)
46 | XCTAssertEqual([2, 3], xs[1...2])
47 | }
48 |
49 | func testRangeReplaceableCollection() {
50 | var xs = NonEmptyArray(1, 2, 3)
51 |
52 | XCTAssertEqual(xs, NonEmptyArray([1, 2, 3]))
53 |
54 | xs.append(4)
55 | XCTAssertEqual(NonEmptyArray(1, 2, 3, 4), xs)
56 | xs.append(contentsOf: [5, 6])
57 | XCTAssertEqual(NonEmptyArray(1, 2, 3, 4, 5, 6), xs)
58 | xs.insert(0, at: 0)
59 | XCTAssertEqual(NonEmptyArray(0, 1, 2, 3, 4, 5, 6), xs)
60 | xs.insert(contentsOf: [-2, -1], at: 0)
61 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6), xs)
62 | xs.insert(contentsOf: [], at: 0)
63 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6), xs)
64 | xs.insert(7, at: 9)
65 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7), xs)
66 | xs.insert(contentsOf: [8, 9], at: 10)
67 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9), xs)
68 | xs += [10]
69 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), xs)
70 | XCTAssertEqual(NonEmptyArray(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), xs + [11])
71 | }
72 |
73 | func testSetAlgebra() {
74 | XCTAssertEqual(3, NonEmptySet(1, 1, 2, 3).count)
75 |
76 | XCTAssertTrue(NonEmptySet(1, 2, 3).contains(1))
77 | XCTAssertTrue(NonEmptySet(1, 2, 3).contains(3))
78 | XCTAssertFalse(NonEmptySet(1, 2, 3).contains(4))
79 |
80 | XCTAssertEqual(NonEmptySet(1, 2, 3, 4, 5, 6), NonEmptySet(1, 2, 3).union(NonEmptySet(4, 5, 6)))
81 | XCTAssertEqual(NonEmptySet(1, 2, 3, 4, 5, 6), NonEmptySet(1, 2, 3).union([4, 5, 6]))
82 | XCTAssertEqual([3], NonEmptySet(1, 2, 3).intersection(NonEmptySet(3, 4, 5)))
83 | XCTAssertEqual([3], NonEmptySet(1, 2, 3).intersection([3, 4, 5]))
84 | XCTAssertEqual([1, 2, 4, 5], NonEmptySet(1, 2, 3).symmetricDifference(NonEmptySet(3, 4, 5)))
85 | XCTAssertEqual([1, 2, 4, 5], NonEmptySet(1, 2, 3).symmetricDifference([3, 4, 5]))
86 |
87 | var xs = NonEmptySet(1, 2, 3)
88 |
89 | XCTAssertEqual(xs, NonEmptySet([1, 2, 3]))
90 |
91 | var (inserted, memberAfterInsert) = xs.insert(1)
92 | XCTAssertFalse(inserted)
93 | XCTAssertEqual(1, memberAfterInsert)
94 | XCTAssertEqual(3, xs.count)
95 | (inserted, memberAfterInsert) = xs.insert(4)
96 | XCTAssertTrue(inserted)
97 | XCTAssertEqual(4, memberAfterInsert)
98 | XCTAssertEqual(4, xs.count)
99 | xs.formUnion(NonEmptySet(5, 6))
100 | XCTAssertEqual(NonEmptySet(1, 2, 3, 4, 5, 6), xs)
101 | xs.formUnion([7, 8])
102 | XCTAssertEqual(NonEmptySet(1, 2, 3, 4, 5, 6, 7, 8), xs)
103 |
104 | XCTAssertEqual([2, 3], NonEmptySet(1, 2, 3).subtracting(NonEmptySet(1)))
105 | XCTAssertEqual([1, 2], NonEmptySet(1, 2, 3).subtracting(NonEmptySet(3)))
106 | XCTAssertEqual([2, 3], NonEmptySet(1, 2, 3).subtracting([1]))
107 | XCTAssertEqual([1, 2], NonEmptySet(1, 2, 3).subtracting([3]))
108 |
109 | XCTAssertTrue(NonEmptySet(1, 2, 3).isSubset(of: NonEmptySet(1, 2, 3)))
110 | XCTAssertTrue(NonEmptySet(1, 2, 3).isSubset(of: [1, 2, 3]))
111 | XCTAssertTrue(NonEmptySet(1, 2, 3).isStrictSubset(of: NonEmptySet(1, 2, 3, 4)))
112 | XCTAssertTrue(NonEmptySet(1, 2, 3).isStrictSubset(of: [1, 2, 3, 4]))
113 | XCTAssertFalse(NonEmptySet(1, 2, 3).isStrictSubset(of: NonEmptySet(1, 2, 3)))
114 | XCTAssertFalse(NonEmptySet(1, 2, 3).isStrictSubset(of: [1, 2, 3]))
115 | XCTAssertTrue(NonEmptySet(1, 2, 3).isSuperset(of: NonEmptySet(1, 2, 3)))
116 | XCTAssertTrue(NonEmptySet(1, 2, 3).isSuperset(of: [1, 2, 3]))
117 | XCTAssertTrue(NonEmptySet(1, 2, 3, 4).isStrictSuperset(of: NonEmptySet(1, 2, 3)))
118 | XCTAssertTrue(NonEmptySet(1, 2, 3, 4).isStrictSuperset(of: [1, 2, 3]))
119 | XCTAssertFalse(NonEmptySet(1, 2, 3).isStrictSuperset(of: NonEmptySet(1, 2, 3)))
120 | XCTAssertFalse(NonEmptySet(1, 2, 3).isStrictSuperset(of: [1, 2, 3]))
121 | XCTAssertTrue(NonEmptySet(1, 2, 3).isDisjoint(with: NonEmptySet(4, 5, 6)))
122 | XCTAssertTrue(NonEmptySet(1, 2, 3).isDisjoint(with: [4, 5, 6]))
123 | XCTAssertFalse(NonEmptySet(1, 2, 3).isDisjoint(with: NonEmptySet(3, 4, 5)))
124 | XCTAssertFalse(NonEmptySet(1, 2, 3).isDisjoint(with: [3, 4, 5]))
125 | }
126 |
127 | func testExpressibleByArrayLiteral() {
128 | let xs = NonEmpty<[Int]>(1, 2, 3)
129 | let ys: NonEmpty<[Int]> = [1, 2, 3]
130 |
131 | XCTAssertEqual(xs, ys)
132 | XCTAssertEqual(xs, [1, 2, 3])
133 | XCTAssertNotEqual(xs, [2, 1, 3])
134 | }
135 |
136 | func testExpressibleByDictionaryLiteral() {
137 | let xs = NonEmpty<[String: String]>(("a", "test"), ["b": "demo"])
138 | let ys: NonEmpty<[String: String]> = ["a": "test", "b": "demo"]
139 |
140 | XCTAssertEqual(xs, ys)
141 | XCTAssertEqual(xs, ["b": "demo", "a": "test"])
142 | XCTAssertEqual(xs.rawValue, ["b": "demo", "a": "test"])
143 | }
144 |
145 | func testDictionary() {
146 | let nonEmptyDict1 = NonEmpty(("1", "Blob"), ["1": "Blobbo"], uniquingKeysWith: { $1 })
147 | XCTAssertEqual(1, nonEmptyDict1.count)
148 | XCTAssertEqual("Blobbo", nonEmptyDict1["1"])
149 | XCTAssertEqual(
150 | "Blob", NonEmpty(("1", "Blob"), ["1": "Blobbo"], uniquingKeysWith: { v, _ in v })["1"])
151 |
152 | let nonEmptySingleton1 = NonEmptyDictionary((key: "1", value: "Blob"))
153 | XCTAssertEqual(1, nonEmptySingleton1.count)
154 |
155 | XCTAssert(
156 | NonEmpty<[String: String]>(("1", "Blob"), ["2": "Blob Senior"])
157 | .merging(["2": "Blob Junior"], uniquingKeysWith: { $1 })
158 | == NonEmpty(("1", "Blob"), ["2": "Blob Junior"])
159 | )
160 | XCTAssert(
161 | NonEmpty<[String: String]>(("1", "Blob"), ["2": "Blob Senior"])
162 | .merging(["2": "Blob Junior"], uniquingKeysWith: { a, _ in a })
163 | == NonEmpty(("1", "Blob"), ["2": "Blob Senior"])
164 | )
165 | }
166 |
167 | func testEquatable() {
168 | XCTAssertEqual(NonEmptyArray(1, 2, 3), NonEmptyArray(1, 2, 3))
169 | XCTAssertNotEqual(NonEmptyArray(1, 2, 3), NonEmptyArray(2, 2, 3))
170 | XCTAssertNotEqual(NonEmptyArray(1, 2, 3), NonEmptyArray(1, 2, 4))
171 | XCTAssertEqual(NonEmptySet(1, 2, 3), NonEmptySet(3, 2, 1))
172 | XCTAssert(
173 | NonEmpty(("hello", "world"), ["goodnight": "moon"])
174 | == NonEmpty(("goodnight", "moon"), ["hello": "world"])
175 | )
176 | }
177 |
178 | func testComparable() {
179 | XCTAssertEqual(2, NonEmptyArray(1, 2, 3).min() + 1)
180 | XCTAssertEqual(2, NonEmptyArray(3, 2, 1).min() + 1)
181 | XCTAssertEqual(2, NonEmptyArray(1).min() + 1)
182 | XCTAssertEqual(4, NonEmptyArray(1, 2, 3).max() + 1)
183 | XCTAssertEqual(4, NonEmptyArray(3, 2, 1).max() + 1)
184 | XCTAssertEqual(4, NonEmptyArray(3).max() + 1)
185 | XCTAssertEqual(NonEmptyArray(1, 2, 3), NonEmptyArray(3, 1, 2).sorted())
186 | XCTAssertEqual(NonEmptyArray(1), NonEmptyArray(1).sorted())
187 | }
188 |
189 | func testCodable() throws {
190 | let xs = NonEmptyArray(1, 2, 3)
191 | XCTAssertEqual(
192 | xs, try JSONDecoder().decode(NonEmptyArray.self, from: JSONEncoder().encode(xs)))
193 | XCTAssertEqual(
194 | xs, try JSONDecoder().decode(NonEmptyArray.self, from: Data("[1,2,3]".utf8)))
195 | XCTAssertThrowsError(try JSONDecoder().decode(NonEmptyArray.self, from: Data("[]".utf8)))
196 |
197 | let str = NonEmptyString(rawValue: "Hello")!
198 | XCTAssertEqual(
199 | [str], try JSONDecoder().decode([NonEmptyString].self, from: JSONEncoder().encode([str])))
200 | XCTAssertEqual(
201 | [str], try JSONDecoder().decode([NonEmptyString].self, from: Data(#"["Hello"]"#.utf8)))
202 | XCTAssertThrowsError(try JSONDecoder().decode([NonEmptyString].self, from: Data(#"[""]"#.utf8)))
203 |
204 | let dict = NonEmpty(rawValue: ["Hello": 1])!
205 | XCTAssertEqual(
206 | dict, try JSONDecoder().decode(NonEmpty<[String: Int]>.self, from: JSONEncoder().encode(dict))
207 | )
208 | XCTAssertEqual(
209 | dict, try JSONDecoder().decode(NonEmpty<[String: Int]>.self, from: Data(#"{"Hello":1}"#.utf8))
210 | )
211 | XCTAssertThrowsError(
212 | try JSONDecoder().decode(NonEmpty<[String: Int]>.self, from: Data("{}".utf8)))
213 |
214 | let data = NonEmpty(rawValue: Data("Hello".utf8))
215 | XCTAssertEqual(
216 | data, try JSONDecoder().decode(NonEmpty.self, from: JSONEncoder().encode(data)))
217 | XCTAssertEqual(
218 | data, try JSONDecoder().decode(NonEmpty.self, from: Data(#""SGVsbG8=""#.utf8)))
219 | XCTAssertThrowsError(try JSONDecoder().decode(NonEmpty.self, from: Data("\"\"".utf8)))
220 | }
221 |
222 | func testNonEmptySetWithTrivialValue() {
223 | let xs = NonEmptySet(.init(value: 1), .init(value: 2))
224 | let ys = NonEmptySet(.init(value: 2), .init(value: 1))
225 |
226 | XCTAssertEqual(xs, ys)
227 | }
228 |
229 | func testMutableCollectionWithArraySlice() {
230 | let numbers = Array(1...10)
231 | var xs = NonEmpty(rawValue: numbers[5...])!
232 | xs[6] = 43
233 | XCTAssertEqual(43, xs[6])
234 | }
235 |
236 | #if canImport(SwiftUI)
237 | func testMove() {
238 | var xs: NonEmptyArray = .init("A", "B", "C")
239 | xs.move(fromOffsets: [1], toOffset: 3)
240 | XCTAssertEqual(.init("A", "C", "B"), xs)
241 | }
242 | #endif
243 | }
244 |
245 | struct TrivialHashable: Equatable, Comparable, Hashable {
246 | let value: Int
247 | static func < (lhs: TrivialHashable, rhs: TrivialHashable) -> Bool {
248 | return lhs.value < rhs.value
249 | }
250 | func hash(into hasher: inout Hasher) {
251 | hasher.combine(self.value)
252 | }
253 | }
254 |
--------------------------------------------------------------------------------