[Issue] Collection.distance() works not very well in some situations

[Issue] Collection.distance() works not very well in some situations
The question is that, whether the original Collection Protocol requires index from lower to higher (startIndex < endIndex).

If the original Collection Protocol requires index from lower to higher, than this infinity loop should not happen:

class MyCollectionA : Collection {
    
    var startIndex: Int {
        return 1
    }
    
    var endIndex: Int {
        return 100
    }
    
    func index(after i: Int) -> Int {
        return i + 2
    }
        
    subscript(position: Int) -> Void {
        return ()
    }
}

let a = MyCollectionA()
a.distance(from: 0, to: 100) // 50
a.distance(from: 1, to: 100) // !! Infinity Loop
a.count // !! Infinity Loop

if we assume the index is from lower to higher, the implementation of the distance(from:to:) should use "<" with "while" to count distance

    var start = start
    var count: IndexDistance = 0
    while start < end { // instead of using !=
      count = count + 1
      formIndex(after: &start)
    }
    return count
  }

If the original Collection Protocol not requires index from to higher, than the code below should works, but unfortunately, the code in Collection.distance does not allow.

···

class MyCollectionB : Collection {
    
    var startIndex: Int {
        return 100
    }
    
    var endIndex: Int {
        return 0
    }
    
    func index(after i: Int) -> Int {
        return i - 2
    }
    
    // start, end, index(after i: Int) -> indices: DefaultIndices
    
    subscript(position: Int) -> Void {
        return ()
    }
}

let b = MyCollectionB()
b.count // !! Fetal Error: Only BidirectionalCollections can have end come before start

`Collection` does require that `startIndex <= endIndex`, and in general, that `i < c.index(after: i)` for all `i` in `c.startIndex ..< c.endIndex`. Unfortunately, this may not be explicitly documented anywhere.

(Also unfortunately, `index(after:)` doesn't appear at all in Apple's documentation for `Collection`!)

···

On Dec 2, 2017, at 12:28 PM, Cao, Jiannan via swift-dev <swift-dev@swift.org> wrote:

The question is that, whether the original Collection Protocol requires index from lower to higher (startIndex < endIndex).

--
Brent Royal-Gordon
Architechies