Last active
November 9, 2020 03:58
-
-
Save ryotapoi/436063f4239d80525e8406356e4f5544 to your computer and use it in GitHub Desktop.
Swiftで高速にCRC32を求める。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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