Skip to content

Instantly share code, notes, and snippets.

@skagedal
Created December 2, 2018 18:40
Show Gist options
  • Save skagedal/ac76a35268f5d9f8505c4df16e6f90f8 to your computer and use it in GitHub Desktop.
Save skagedal/ac76a35268f5d9f8505c4df16e6f90f8 to your computer and use it in GitHub Desktop.
Implemented for AoC 2018, first question
import Foundation
/// Represents a sequence of Data split at a certain value
struct DataSplitSequence: Sequence {
typealias Element = Data
struct Iterator: IteratorProtocol {
private let sequence: DataSplitSequence
private var index: Int = -1
init(_ sequence: DataSplitSequence) {
self.sequence = sequence
}
typealias Element = Data
public mutating func next() -> Data? {
guard index < sequence.data.count else {
return nil
}
let startIndex = index + 1
repeat {
index += 1
} while index < sequence.data.count && sequence.data[index] != sequence.separator
return sequence.data[startIndex..<index]
}
}
private let data: Data
private let separator: UInt8
init(data: Data, separator: UInt8) {
self.data = data
self.separator = separator
}
func makeIterator() -> DataSplitSequence.Iterator {
return Iterator(self)
}
}
extension Data {
func splitSequence(separator: UInt8) -> DataSplitSequence {
return DataSplitSequence(data: self, separator: separator)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment