home: hub: hare-crc32

ref: fdb251d1136d8b8a92c520fc0bf6ae7adbcfe154
dir: /crc.ha/

View raw version
// Copyright (c) 2022 grobe0ba (grobe0ba@tcp80.org)
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

use strings;
use types::c;

export fn crc32(crc: u32, inbuf: []u8) u32 = {
	crc = crc ^ ~0;

	for (let i = 0z; i < len(inbuf); i += 1) {
		crc = crc32_tab[(crc ^ inbuf[i]) & 0xff] ^ (crc >> 8);
	};

	return crc ^ ~0;
};

@test fn crc32() void = {
	const ts: str = "harelang";
	const tc: *c::char = c::fromstr(ts);
	defer free(tc);
	const ta = (tc: *[*]u8)[..len(ts)];

	const sum: u32 = crc32(0, ta);

	assert(sum == 0x4c982cbf);
};