@@ -91,27 +91,22 @@ extension Product2: Collection where Base1: Collection {
91
91
}
92
92
93
93
public var startIndex : Index {
94
- base1 . isEmpty || base2 . isEmpty
95
- ? endIndex
96
- : Index ( i1 : base1 . startIndex , i2: base2. startIndex)
94
+ Index (
95
+ i1 : base2 . isEmpty ? base1 . endIndex : base1 . startIndex ,
96
+ i2: base2. startIndex)
97
97
}
98
98
99
99
public var endIndex : Index {
100
- Index ( i1: base1. endIndex, i2: base2. endIndex)
100
+ // `base2.startIndex` simplifies index calculations.
101
+ Index ( i1: base1. endIndex, i2: base2. startIndex)
101
102
}
102
103
103
104
public func index( after i: Index ) -> Index {
104
- precondition ( i. i1 != base1. endIndex && i. i2 != base2. endIndex,
105
- " Can't advance past endIndex " )
105
+ precondition ( i. i1 != base1. endIndex, " Can't advance past endIndex " )
106
106
let newIndex2 = base2. index ( after: i. i2)
107
- if newIndex2 < base2. endIndex {
108
- return Index ( i1: i. i1, i2: newIndex2)
109
- }
110
-
111
- let newIndex1 = base1. index ( after: i. i1)
112
- return newIndex1 == base1. endIndex
113
- ? endIndex
114
- : Index ( i1: newIndex1, i2: base2. startIndex)
107
+ return newIndex2 == base2. endIndex
108
+ ? Index ( i1: base1. index ( after: i. i1) , i2: base2. startIndex)
109
+ : Index ( i1: i. i1, i2: newIndex2)
115
110
}
116
111
117
112
// TODO: Implement index(_:offsetBy:) and index(_:offsetBy:limitedBy:)
@@ -125,7 +120,7 @@ extension Product2: Collection where Base1: Collection {
125
120
}
126
121
127
122
return base2 [ start. i2... ] . count + base2[ ..< end. i2] . count
128
- + base2. count * ( base1. distance ( from: start. i1, to: end. i1) )
123
+ + base2. count * ( base1. distance ( from: start. i1, to: end. i1) - 1 )
129
124
}
130
125
131
126
public subscript( position: Index ) -> ( Base1 . Element , Base2 . Element ) {
@@ -140,12 +135,12 @@ extension Product2: BidirectionalCollection
140
135
precondition ( i != startIndex,
141
136
" Can't move before startIndex " )
142
137
if i. i2 == base2. startIndex {
138
+ return Index (
139
+ i1: base1. index ( before: i. i1) ,
140
+ i2: base2. index ( before: base2. endIndex) )
141
+ } else {
143
142
return Index ( i1: i. i1, i2: base2. index ( before: i. i2) )
144
143
}
145
-
146
- return Index (
147
- i1: base1. index ( before: i. i1) ,
148
- i2: base2. index ( before: base2. endIndex) )
149
144
}
150
145
}
151
146
0 commit comments