libacfutils
A general purpose library of utility functions designed to make it easier to develop addons for the X-Plane flight simulator.
Loading...
Searching...
No Matches
crc64.c
1/*
2 * CDDL HEADER START
3 *
4 * This file and its contents are supplied under the terms of the
5 * Common Development and Distribution License ("CDDL"), version 1.0.
6 * You may only use this file in accordance with the terms of version
7 * 1.0 of the CDDL.
8 *
9 * A full copy of the text of the CDDL should have accompanied this
10 * source. A copy of the CDDL is also available via the Internet at
11 * http://www.illumos.org/license/CDDL.
12 *
13 * CDDL HEADER END
14*/
15/*
16 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
17 */
18/*
19 * Copyright 2023 Saso Kiselkov. All rights reserved.
20 */
21
22#include <math.h>
23
24#include <acfutils/crc64.h>
25
27#define CRC64_POLY 0xC96C5795D7870F42ULL
28
29static uint64_t crc64_table[256];
30static uint64_t rand_seed = 0;
31
36void
38{
39 for (int i = 0; i < 256; i++) {
40 uint64_t *ct;
41 int j;
42 for (ct = crc64_table + i, *ct = i, j = 8; j > 0; j--)
43 *ct = (*ct >> 1) ^ (-(*ct & 1) & CRC64_POLY);
44 }
45}
46
50void
52{
53 ASSERT(crc != NULL);
55}
56
64uint64_t
65crc64(const void *input, size_t sz)
66{
67 uint64_t crc;
68
69 crc64_state_init(&crc);
70 return (crc64_append(crc, input, sz));
71}
72
87uint64_t
88crc64_append(uint64_t crc, const void *input, size_t sz)
89{
90 const uint8_t *in_bytes = input;
91
92 ASSERT3U(crc64_table[128], ==, CRC64_POLY);
93 for (size_t i = 0; i < sz; i++)
94 crc = (crc >> 8) ^ crc64_table[(crc ^ in_bytes[i]) & 0xFF];
95
96 return (crc);
97}
98
105void
106crc64_srand(uint64_t seed)
107{
108 rand_seed = seed;
109}
110
122uint64_t
124{
125 rand_seed = crc64(&rand_seed, sizeof (rand_seed));
126 return (rand_seed);
127}
128
134double
136{
137 return (crc64_rand() / (double)UINT64_MAX);
138}
139
146double
147crc64_rand_normal(double sigma)
148{
149 double x = crc64_rand_fract();
150 double y = crc64_rand_fract();
151 double z = sqrt(-2 * log(x)) * cos(2 * M_PI * y);
152 return (sigma * z);
153}
#define ASSERT3U(x, op, y)
Definition assert.h:210
#define ASSERT(x)
Definition assert.h:208
API_EXPORT uint64_t crc64(const void *input, size_t sz)
Definition crc64.c:65
API_EXPORT void crc64_state_init_impl(uint64_t *crc)
Definition crc64.c:51
API_EXPORT void crc64_srand(uint64_t seed)
Definition crc64.c:106
API_EXPORT void crc64_init(void)
Definition crc64.c:37
API_EXPORT uint64_t crc64_append(uint64_t crc, const void *input, size_t sz)
Definition crc64.c:88
API_EXPORT double crc64_rand_normal(double sigma)
Definition crc64.c:147
static void crc64_state_init(uint64_t *crc)
Definition crc64.h:48
API_EXPORT uint64_t crc64_rand(void)
Definition crc64.c:123
API_EXPORT double crc64_rand_fract(void)
Definition crc64.c:135