Skip to content

Commit

Permalink
better-document CRC32
Browse files Browse the repository at this point in the history
  • Loading branch information
tayloraswift committed Jun 3, 2024
1 parent 7798c34 commit 0f1afe0
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions Sources/CRC/CRC32.swift
Original file line number Diff line number Diff line change
@@ -1,39 +1,48 @@
import Base16

/// The value of a [CRC32](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) checksum.
@frozen public
struct CRC32:Hashable, Sendable
{
@_documentation(visibility: internal)
public static
let table:[UInt32] = (0 ..< 256).map
{
(i:UInt32) in
(0 ..< 8).reduce(i){ (c, _) in (c & 1 * 0xed_b8_83_20) ^ c >> 1 }
}

/// The checksum value as a 32-bit unsigned integer.
public
var checksum:UInt32

/// Creates a new checksum with the specified value.
@inlinable public
init(checksum:UInt32 = 0)
{
self.checksum = checksum
}

/// Computes the checksum of the provided message.
@inlinable public
init(hashing message:some Sequence<UInt8>)
init(hashing message:borrowing some Sequence<UInt8>)
{
self.init()
self.update(with: message)
}

/// Returns a new checksum by hashing the provided message into the current checksum.
@inlinable public
func updated(with message:some Sequence<UInt8>) -> Self
func updated(with message:borrowing some Sequence<UInt8>) -> Self
{
var checksum:Self = self
checksum.update(with: message)
return checksum
}

/// Updates the checksum by hashing the provided message into the existing checksum.
@inlinable public mutating
func update(with message:some Sequence<UInt8>)
func update(with message:borrowing some Sequence<UInt8>)
{
self.checksum = ~message.reduce(~self.checksum)
{
Expand All @@ -52,6 +61,7 @@ extension CRC32:ExpressibleByIntegerLiteral
}
extension CRC32:CustomStringConvertible
{
/// The lowercased hexadecimal representation of the checksum value.
@inlinable public
var description:String
{
Expand Down

0 comments on commit 0f1afe0

Please sign in to comment.