view toys/posix/cksum.c @ 674:7e846e281e38

New build infrastructure to generate FLAG_ macros and TT alias, #define FOR_commandname before #including toys.h to trigger it. Rename DEFINE_GLOBALS() to just GLOBALS() (because I could never remember if it was DECLARE_GLOBALS). Convert existing commands to use new infrastructure, and replace optflag constants with FLAG_ macros where appropriate.
author Rob Landley <>
date Mon, 08 Oct 2012 00:02:30 -0500
parents 6df4ccc0acbe
children 786841fdb1e0
line wrap: on
line source

/* vi: set sw=4 ts=4:
 * cksum.c - produce crc32 checksum value for each input
 * Copyright 2008 Rob Landley <>
 * See


config CKSUM
	bool "cksum"
	default y
	  usage: cksum [-IPLN] [file...]

	  For each file, output crc32 checksum value, length and name of file.
	  If no files listed, copy from stdin.  Filename "-" is a synonym for stdin.

	  -L	Little endian (defaults to big endian)
	  -P	Pre-inversion
	  -I	Skip post-inversion
	  -N	Do not include length in CRC calculation

#define FOR_cksum
#include "toys.h"

	unsigned crc_table[256];

static unsigned cksum_be(unsigned crc, unsigned char c)
	return (crc<<8)^TT.crc_table[(crc>>24)^c];

static unsigned cksum_le(unsigned crc, unsigned char c)
	return TT.crc_table[(crc^c)&0xff] ^ (crc>>8);

static void do_cksum(int fd, char *name)
	unsigned crc = (toys.optflags&4) ? 0xffffffff : 0;
	uint64_t llen = 0, llen2;
	unsigned (*cksum)(unsigned crc, unsigned char c);

	cksum = (toys.optflags&2) ? cksum_le : cksum_be;
	// CRC the data

	for (;;) {
		int len, i;

		len = read(fd, toybuf, sizeof(toybuf));
		if (len<0) {
			toys.exitval = EXIT_FAILURE;
		if (len<1) break;

		llen += len;
		for (i=0; i<len; i++) crc=cksum(crc, toybuf[i]);

	// CRC the length

	llen2 = llen;
	if (!(toys.optflags&1)) {
		while (llen) {
			crc = cksum(crc, llen);
			llen >>= 8;

	printf("%u %"PRIu64, (toys.optflags&8) ? crc : ~crc, llen2);
	if (strcmp("-", name)) printf(" %s", name);

void cksum_main(void)
	crc_init(TT.crc_table, toys.optflags&2);
	loopfiles(toys.optargs, do_cksum);