The first is copied from https://github.com/apple/swift/pull/13930's contribution (with a minor bug fix applied). The second is an adaptation that tries to avoid creating copies and operate using indices directly.