2022-01-04 12:21:08 +03:00
|
|
|
// Copyright (c) 2019-2022 Alexander Medvednikov. All rights reserved.
|
2019-07-13 16:11:32 +03:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// This is a very basic crc32 implementation
|
|
|
|
// at the moment with no architecture optimizations
|
|
|
|
module crc32
|
|
|
|
|
|
|
|
// polynomials
|
2020-03-11 03:31:24 +03:00
|
|
|
pub const (
|
2020-04-08 16:48:13 +03:00
|
|
|
ieee = u32(0xedb88320)
|
|
|
|
castagnoli = u32(0x82f63b78)
|
|
|
|
koopman = u32(0xeb31d82e)
|
2019-07-13 16:11:32 +03:00
|
|
|
)
|
|
|
|
|
2019-07-15 18:49:01 +03:00
|
|
|
// The size of a CRC-32 checksum in bytes.
|
|
|
|
const (
|
2019-10-24 14:48:20 +03:00
|
|
|
size = 4
|
2019-07-15 18:49:01 +03:00
|
|
|
)
|
|
|
|
|
2019-07-13 16:11:32 +03:00
|
|
|
struct Crc32 {
|
|
|
|
mut:
|
|
|
|
table []u32
|
|
|
|
}
|
|
|
|
|
2023-01-15 23:37:09 +03:00
|
|
|
// generate_table populates a 256-word table from the specified polynomial `poly`
|
|
|
|
// to represent the polynomial for efficient processing.
|
2021-05-08 13:32:29 +03:00
|
|
|
fn (mut c Crc32) generate_table(poly int) {
|
|
|
|
for i in 0 .. 256 {
|
2019-07-13 16:11:32 +03:00
|
|
|
mut crc := u32(i)
|
2021-05-08 13:32:29 +03:00
|
|
|
for _ in 0 .. 8 {
|
2019-11-06 01:02:50 +03:00
|
|
|
if crc & u32(1) == u32(1) {
|
|
|
|
crc = (crc >> 1) ^ u32(poly)
|
2019-07-13 16:11:32 +03:00
|
|
|
} else {
|
|
|
|
crc >>= u32(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.table << crc
|
|
|
|
}
|
|
|
|
}
|
2019-12-06 15:24:53 +03:00
|
|
|
|
2022-04-15 15:35:35 +03:00
|
|
|
fn (c &Crc32) sum32(b []u8) u32 {
|
2019-07-13 16:11:32 +03:00
|
|
|
mut crc := ~u32(0)
|
2021-05-08 13:32:29 +03:00
|
|
|
for i in 0 .. b.len {
|
2022-04-15 14:58:56 +03:00
|
|
|
crc = c.table[u8(crc) ^ b[i]] ^ (crc >> 8)
|
2019-07-13 16:11:32 +03:00
|
|
|
}
|
|
|
|
return ~crc
|
|
|
|
}
|
|
|
|
|
2023-01-15 23:37:09 +03:00
|
|
|
// checksum returns the CRC-32 checksum of data `b` by using the polynomial represented by
|
|
|
|
// `c`'s table.
|
2022-04-15 15:35:35 +03:00
|
|
|
pub fn (c &Crc32) checksum(b []u8) u32 {
|
2019-08-03 04:40:54 +03:00
|
|
|
return c.sum32(b)
|
2019-07-13 16:11:32 +03:00
|
|
|
}
|
|
|
|
|
2023-01-15 23:37:09 +03:00
|
|
|
// new creates a `Crc32` polynomial.
|
2019-09-13 22:45:04 +03:00
|
|
|
pub fn new(poly int) &Crc32 {
|
2019-07-13 16:11:32 +03:00
|
|
|
mut c := &Crc32{}
|
|
|
|
c.generate_table(poly)
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2023-01-15 23:37:09 +03:00
|
|
|
// sum calculates the CRC-32 checksum of `b` by using the IEEE polynomial.
|
2022-04-15 15:35:35 +03:00
|
|
|
pub fn sum(b []u8) u32 {
|
2021-05-08 13:32:29 +03:00
|
|
|
c := new(int(crc32.ieee))
|
2019-08-03 04:40:54 +03:00
|
|
|
return c.sum32(b)
|
2019-07-13 16:11:32 +03:00
|
|
|
}
|