aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/vlib/hash/crc32
diff options
context:
space:
mode:
authorIndrajith K L2022-12-03 17:00:20 +0530
committerIndrajith K L2022-12-03 17:00:20 +0530
commitf5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch)
tree2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/old/vlib/hash/crc32
downloadcli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.tar.gz
cli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.tar.bz2
cli-tools-windows-f5c4671bfbad96bf346bd7e9a21fc4317b4959df.zip
Adds most of the toolsHEADmaster
Diffstat (limited to 'v_windows/v/old/vlib/hash/crc32')
-rw-r--r--v_windows/v/old/vlib/hash/crc32/crc32.v63
-rw-r--r--v_windows/v/old/vlib/hash/crc32/crc32_test.v14
2 files changed, 77 insertions, 0 deletions
diff --git a/v_windows/v/old/vlib/hash/crc32/crc32.v b/v_windows/v/old/vlib/hash/crc32/crc32.v
new file mode 100644
index 0000000..d29aa12
--- /dev/null
+++ b/v_windows/v/old/vlib/hash/crc32/crc32.v
@@ -0,0 +1,63 @@
+// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
+// 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 (
+ ieee = u32(0xedb88320)
+ castagnoli = u32(0x82f63b78)
+ koopman = u32(0xeb31d82e)
+)
+
+// The size of a CRC-32 checksum in bytes.
+const (
+ size = 4
+)
+
+struct Crc32 {
+mut:
+ table []u32
+}
+
+fn (mut c Crc32) generate_table(poly int) {
+ for i in 0 .. 256 {
+ mut crc := u32(i)
+ for _ in 0 .. 8 {
+ if crc & u32(1) == u32(1) {
+ crc = (crc >> 1) ^ u32(poly)
+ } else {
+ crc >>= u32(1)
+ }
+ }
+ c.table << crc
+ }
+}
+
+fn (c &Crc32) sum32(b []byte) u32 {
+ mut crc := ~u32(0)
+ for i in 0 .. b.len {
+ crc = c.table[byte(crc) ^ b[i]] ^ (crc >> 8)
+ }
+ return ~crc
+}
+
+pub fn (c &Crc32) checksum(b []byte) u32 {
+ return c.sum32(b)
+}
+
+// pass the polynomial to use
+pub fn new(poly int) &Crc32 {
+ mut c := &Crc32{}
+ c.generate_table(poly)
+ return c
+}
+
+// calculate crc32 using ieee
+pub fn sum(b []byte) u32 {
+ c := new(int(crc32.ieee))
+ return c.sum32(b)
+}
diff --git a/v_windows/v/old/vlib/hash/crc32/crc32_test.v b/v_windows/v/old/vlib/hash/crc32/crc32_test.v
new file mode 100644
index 0000000..7355179
--- /dev/null
+++ b/v_windows/v/old/vlib/hash/crc32/crc32_test.v
@@ -0,0 +1,14 @@
+import hash.crc32
+
+fn test_hash_crc32() {
+ b1 := 'testing crc32'.bytes()
+ sum1 := crc32.sum(b1)
+ assert sum1 == u32(1212124400)
+ assert sum1.hex() == '483f8cf0'
+
+ c := crc32.new(int(crc32.ieee))
+ b2 := 'testing crc32 again'.bytes()
+ sum2 := c.checksum(b2)
+ assert sum2 == u32(1420327025)
+ assert sum2.hex() == '54a87871'
+}