1 /*-------------------------------------------------------------------------
5 * This file supplies pg_erand48(), pg_lrand48(), and pg_srand48(), which
6 * are just like erand48(), lrand48(), and srand48() except that we use
7 * our own implementation rather than the one provided by the operating
8 * system. We used to test for an operating system version rather than
9 * unconditionally using our own, but (1) some versions of Cygwin have a
10 * buggy erand48() that always returns zero and (2) as of 2011, glibc's
11 * erand48() is strangely coded to be almost-but-not-quite thread-safe,
12 * which doesn't matter for the backend but is important for pgbench.
15 * Copyright (c) 1993 Martin Birgmeier
16 * All rights reserved.
18 * You may redistribute unmodified or modified versions of this source
19 * code provided that the above copyright notice and this and the
20 * following conditions are retained.
22 * This software is provided ``as is'', and comes with no warranties
23 * of any kind. I shall in no event be liable for anything that happens
24 * to anyone/anything when using this software.
29 *-------------------------------------------------------------------------
36 #define RAND48_SEED_0 (0x330e)
37 #define RAND48_SEED_1 (0xabcd)
38 #define RAND48_SEED_2 (0x1234)
39 #define RAND48_MULT_0 (0xe66d)
40 #define RAND48_MULT_1 (0xdeec)
41 #define RAND48_MULT_2 (0x0005)
42 #define RAND48_ADD (0x000b)
44 static unsigned short _rand48_seed[3] = {
49 static unsigned short _rand48_mult[3] = {
54 static unsigned short _rand48_add = RAND48_ADD;
58 _dorand48(unsigned short xseed[3])
61 unsigned short temp[2];
63 accu = (unsigned long) _rand48_mult[0] * (unsigned long) xseed[0] +
64 (unsigned long) _rand48_add;
65 temp[0] = (unsigned short) accu; /* lower 16 bits */
66 accu >>= sizeof(unsigned short) * 8;
67 accu += (unsigned long) _rand48_mult[0] * (unsigned long) xseed[1] +
68 (unsigned long) _rand48_mult[1] * (unsigned long) xseed[0];
69 temp[1] = (unsigned short) accu; /* middle 16 bits */
70 accu >>= sizeof(unsigned short) * 8;
71 accu += _rand48_mult[0] * xseed[2] + _rand48_mult[1] * xseed[1] + _rand48_mult[2] * xseed[0];
74 xseed[2] = (unsigned short) accu;
79 pg_erand48(unsigned short xseed[3])
82 return ldexp((double) xseed[0], -48) +
83 ldexp((double) xseed[1], -32) +
84 ldexp((double) xseed[2], -16);
90 _dorand48(_rand48_seed);
91 return ((long) _rand48_seed[2] << 15) + ((long) _rand48_seed[1] >> 1);
95 pg_jrand48(unsigned short xseed[3])
98 return ((long) xseed[2] << 16) + ((long) xseed[1]);
102 pg_srand48(long seed)
104 _rand48_seed[0] = RAND48_SEED_0;
105 _rand48_seed[1] = (unsigned short) seed;
106 _rand48_seed[2] = (unsigned short) (seed >> 16);
107 _rand48_mult[0] = RAND48_MULT_0;
108 _rand48_mult[1] = RAND48_MULT_1;
109 _rand48_mult[2] = RAND48_MULT_2;
110 _rand48_add = RAND48_ADD;