Skip to content

Instantly share code, notes, and snippets.

@ryotapoi
Last active November 9, 2020 03:58
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 ryotapoi/436063f4239d80525e8406356e4f5544 to your computer and use it in GitHub Desktop.
Save ryotapoi/436063f4239d80525e8406356e4f5544 to your computer and use it in GitHub Desktop.
Swiftで高速にCRC32を求める。
import Foundation
import zlib
struct CRC32: Equatable, ExpressibleByIntegerLiteral, CustomStringConvertible {
typealias IntegerLiteralType = UInt32
let value: UInt32
var description: String { String(format: "%08X", value) }
init(data: Data) {
value = data.withUnsafeBytes {
UInt32(crc32(0, $0.bindMemory(to: UInt8.self).baseAddress, numericCast(data.count)))
}
}
init?<T: DataProtocol>(data: T) {
guard let value = data.withContiguousStorageIfAvailable({
UInt32(crc32(0, $0.baseAddress, numericCast(data.count)))
}) else {
return nil
}
self.value = value
}
init(value: UInt32) {
self.value = value
}
init(integerLiteral value: UInt32) {
self.value = value
}
static func ~=(crc32: CRC32, value: UInt32) -> Bool {
crc32.value == value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment