v/vlib/hash/crc32/crc32.v

64 lines
1.1 KiB
V
Raw Normal View History

2022-01-04 10:21:08 +01:00
// Copyright (c) 2019-2022 Alexander Medvednikov. All rights reserved.
2019-07-13 15:11:32 +02: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
pub const (
2020-04-08 15:48:13 +02:00
ieee = u32(0xedb88320)
castagnoli = u32(0x82f63b78)
koopman = u32(0xeb31d82e)
2019-07-13 15:11:32 +02:00
)
2019-07-15 17:49:01 +02:00
// The size of a CRC-32 checksum in bytes.
const (
2019-10-24 13:48:20 +02:00
size = 4
2019-07-15 17:49:01 +02:00
)
2019-07-13 15:11:32 +02:00
struct Crc32 {
mut:
table []u32
}
fn (mut c Crc32) generate_table(poly int) {
for i in 0 .. 256 {
2019-07-13 15:11:32 +02:00
mut crc := u32(i)
for _ in 0 .. 8 {
if crc & u32(1) == u32(1) {
crc = (crc >> 1) ^ u32(poly)
2019-07-13 15:11:32 +02:00
} else {
crc >>= u32(1)
}
}
c.table << crc
}
}
fn (c &Crc32) sum32(b []byte) u32 {
2019-07-13 15:11:32 +02:00
mut crc := ~u32(0)
for i in 0 .. b.len {
crc = c.table[byte(crc) ^ b[i]] ^ (crc >> 8)
2019-07-13 15:11:32 +02:00
}
return ~crc
}
pub fn (c &Crc32) checksum(b []byte) u32 {
return c.sum32(b)
2019-07-13 15:11:32 +02:00
}
2021-02-15 16:52:45 +01:00
// pass the polynomial to use
2019-09-13 21:45:04 +02:00
pub fn new(poly int) &Crc32 {
2019-07-13 15:11:32 +02:00
mut c := &Crc32{}
c.generate_table(poly)
return c
}
2019-10-24 13:48:20 +02:00
// calculate crc32 using ieee
pub fn sum(b []byte) u32 {
c := new(int(crc32.ieee))
return c.sum32(b)
2019-07-13 15:11:32 +02:00
}