File: mmh.c

package info (click to toggle)
libmurmurhash 1.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 160 kB
  • sloc: ansic: 937; makefile: 42; sh: 13
file content (95 lines) | stat: -rw-r--r-- 1,956 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//-----------------------------------------------------------------------------
// libmurmurhash was written by Fabian Klötzl, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "murmurhash.h"

__attribute__((noreturn)) void usage(int exit_code);

int main(int argc, char *argv[])
{
	const char *file_name = NULL;
	int opt = 0;
	while ((opt = getopt(argc, argv, "h")) != -1) {
		if (opt == 'h') {
			usage(EXIT_SUCCESS);
		}
		if (opt == '?') {
			usage(EXIT_FAILURE);
		}
	}

	argc -= optind, argv += optind;

	if (argc == 0) {
		usage(EXIT_FAILURE);
	}

	file_name = argv[0];

	int fd = open(file_name, O_RDONLY);
	if (fd == -1) {
		err(errno, "%s: failed to open file", file_name);
	}

	struct stat sb;
	if (fstat(fd, &sb) == -1) {
		err(errno, "%s: failed to get stats", file_name);
	}

	size_t length = sb.st_size;
	void *data = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0);
	if (data == (void *)-1) {
		err(errno, "%s: failed to map file", file_name);
	}

	// new interface
	uint32_t hash4;
	lmmh_x86_32(data, length, 0, &hash4);
	printf("%" PRIx32 "", hash4);

	uint32_t hash5[4];
	lmmh_x86_128(data, length, 0, hash5);
	printf("  ");
	for (int i = 0; i < 4; i++) {
		printf("%" PRIx32 "", hash5[i]);
	}

	uint64_t hash6[2];
	lmmh_x64_128(data, length, 0, hash6);
	printf("  ");
	for (int i = 0; i < 2; i++) {
		printf("%" PRIx64 "", hash6[i]);
	}

	printf("\n");

	munmap(data, length);
	close(fd);
	return 0;
}

void usage(int exit_code)
{
	static const char str[] = {
		"mmh FILE\n"
		"Compute the murmurhash of a file.\n\n"
		"  -h      Print help\n" //
	};

	fprintf(exit_code == EXIT_SUCCESS ? stdout : stderr, str);
	exit(exit_code);
}