~blainsmith/hare-icmp

18be89f6e87312edad7834cc0a0aef7d32739bc8 — Conrad Hoffmann 3 months ago fdc89fa
Fix checksum calculation and test it

Signed-off-by: Conrad Hoffmann <ch@bitfehler.net>
2 files changed, 11 insertions(+), 8 deletions(-)

M net/icmp/+test.ha
M net/icmp/message.ha
M net/icmp/+test.ha => net/icmp/+test.ha +5 -0
@@ 18,6 18,7 @@ use bytes;
	let outbuf = memio::dynamic();
	let encsz = encode(&outbuf, &inmsg)!;
	assert(encsz == 13);
	assert(inmsg.checksum == 8672);

	let msg = memio::buffer(&outbuf);



@@ 60,6 61,7 @@ use bytes;
	let outbuf = memio::dynamic();
	let encsz = encode(&outbuf, &inmsg)!;
	assert(encsz == 13);
	assert(inmsg.checksum == 10720);

	let msg = memio::buffer(&outbuf);



@@ 98,6 100,7 @@ use bytes;
	let outbuf = memio::dynamic();
	let encsz = encode(&outbuf, &inmsg)!;
	assert(encsz == 4);
	assert(inmsg.checksum == 64757);

	let msg = memio::buffer(&outbuf);



@@ 129,6 132,7 @@ use bytes;
	let outbuf = memio::dynamic();
	let encsz = encode(&outbuf, &inmsg)!;
	assert(encsz == 4);
	assert(inmsg.checksum == 62709);

	let msg = memio::buffer(&outbuf);



@@ 161,6 165,7 @@ use bytes;
	let outbuf = memio::dynamic();
	let encsz = encode(&outbuf, &inmsg)!;
	assert(encsz == 6);
	assert(inmsg.checksum == 62440);

	let msg = memio::buffer(&outbuf);


M net/icmp/message.ha => net/icmp/message.ha +6 -8
@@ 56,21 56,19 @@ fn checksum(msg: []u8) u16 = {
	let cov: size = len(msg) - 1z;

	let s: u32 = 0;
	for (let i = 0z; i < cov; i += 1) {
		s += ((msg[i + 1]: u32) << 8) | msg[i]: u32;
	for (let i = 0z; i < cov; i += 2) {
		s += ((msg[i]: u32) << 8) + msg[i + 1]: u32;
	};

	if (cov & 1 == 0) {
		s += msg[cov]: u32;
	};

	s = (s >> 16) + (s & 0xffff);

	s = s + (s >> 16);

	s ^= s: u16;
	for ((s >> 16) != 0) {
		s = (s >> 16) + (s & 0xffff);
	};

	return s: u16;
	return ~s: u16;
};

// Encodes a [[message]] into the [[io::handle]] provided