Optimizing Swift: Adler32 Checksum

Nice, this is even faster than the complex version I had ported from C.

func taylor_adler32Checksum(of data: Data) -> UInt32 {
    data.withUnsafeBytes { pointer in
        let (q, r): (Int, Int) = data.count.quotientAndRemainder(dividingBy: 5552)
        var (single, double): (UInt32, UInt32) = (1 & 0xffff, (1 >> 16) & 0xffff)

        for i: Int in 0 ..< q {
            for j: Int in 5552 * i ..< 5552 * (i + 1) {
                single &+= .init(pointer[j])
                double &+= single
            }
            single %= 65521
            double %= 65521
        }

        for j: Int in 5552 * q ..< 5552 * q + r {
            single &+= .init(pointer[j])
            double &+= single
        }

        return ((double % 65521) << 16 | (single % 65521)).bigEndian
    }
}

This implementation is 6.2x slower than libz (through DataCompression), while the previous version ported from C is 7.8x.

1 Like