BlueSocket icon indicating copy to clipboard operation
BlueSocket copied to clipboard

Feature request: Make Socket conform to Sequence

Open jverkoey opened this issue 6 years ago • 1 comments

E.g. a rough implementation might look like so:


extension Socket: Sequence {
  public func makeIterator() -> AnyIterator<UInt8> {
    var iterator: Data.Iterator? = nil

    return AnyIterator {
      if let next = iterator?.next() {
        return next
      }

      do {
        var buffer = Data(capacity: self.readBufferSize)
        let _ = try self.read(into: &buffer)
        iterator = buffer.makeIterator()
      } catch let error {
        assertionFailure(error.localizedDescription)
        return nil
      }

      return iterator?.next()
    }
  }
}

This would allow data from the packet to be read as a continuous stream of bytes, even across multiple internal socket.read calls.

jverkoey avatar Feb 02 '19 02:02 jverkoey

Not a bad idea. Can you give me a usage example? Thanks.

billabt avatar Feb 08 '19 14:02 billabt