Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Last active November 17, 2016 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaSullivan/72b7adcb9c5f0cf4cad6 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/72b7adcb9c5f0cf4cad6 to your computer and use it in GitHub Desktop.
This is a simple Sequence type that accepts an array and sequentially returns the elements, looping back to the first as needed until the required number of elements has been generated.
//: # RepeatingSequence
import Swift
import Foundation
struct RepeatingSequence<T>: Sequence {
/// The Collection that we base our sequence on. We use a Collection and not
/// another Sequence because Sequences are not guaranteed to be repeatedly iterated.
let data: AnyCollection<T>
/// We can optionally specify a maximum number of iterations. This is necessary
/// to create non-infinite Sequences.
let maxCount: Int?
func makeIterator() -> AnyIterator<T> {
var index: AnyCollection.Index = data.startIndex
var count: Int = 0
return AnyIterator<T> {
if let max = self.maxCount, count >= max {
return nil
}
defer {
index = self.data.index(after: index)
if index == self.data.endIndex {
index = self.data.startIndex
}
count += 1
}
return self.data[index]
}
}
}
let apiKey = "abcdefghijklmnopqrstuvwxyz"
let nonceCollection = AnyCollection("This is my nonce.".utf8)
let nonceSequence = RepeatingSequence(data: nonceCollection, maxCount: nil)
let encodeSeq = zip(apiKey.utf8, nonceSequence)
let outBytes: [UInt8] = encodeSeq.map({$0.0 ^ $0.1})
print(outBytes)
let decodeZip = zip(outBytes, nonceSequence)
let bytes = decodeZip.map({$0.0 ^ $0.1})
if let reconstitutedString = String(bytes: bytes, encoding: String.Encoding.utf8) {
print(reconstitutedString)
print("Strings match: \(apiKey == reconstitutedString)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment