fix compile errors
[wdl/wdl-ol.git] / WDL / rng.cpp
blobe02dc2efda507731c0ef7402a9cf96fc668083c9
1 /*
2 WDL - rng.cpp
3 Copyright (C) 2005 and later, Cockos Incorporated
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
25 This file provides the implementation of a decent random number generator,
26 that internally uses a 256-bit state, and SHA-1 to iterate.
30 #ifdef _WIN32
31 #include <windows.h>
32 #else
33 #include <stdlib.h>
34 #include <memory.h>
35 #include <string.h>
36 #endif
39 #include "rng.h"
40 #include "sha.h"
42 static unsigned char state[32];
44 void WDL_RNG_addentropy(void *buf, int buflen)
46 WDL_SHA1 tmp;
47 tmp.add(state,sizeof(state));
48 tmp.result(state);
49 tmp.reset();
50 tmp.add((unsigned char *)buf,buflen);
51 tmp.result(state+sizeof(state) - WDL_SHA1SIZE);
54 static void rngcycle()
56 int i;
57 for (i = 0; i < (int)sizeof(state) && state[i]++; i++);
60 int WDL_RNG_int32()
62 WDL_SHA1 tmp;
63 tmp.add(state,sizeof(state));
64 rngcycle();
65 union {
66 char buf[WDL_SHA1SIZE];
67 int a;
68 } b;
69 tmp.result(b.buf);
70 return b.a;
75 void WDL_RNG_bytes(void *buf, int buflen)
77 char *b=(char *)buf;
78 while (buflen > 0)
80 char tb[WDL_SHA1SIZE];
81 WDL_SHA1 tmp;
82 tmp.add(state,sizeof(state));
83 rngcycle();
85 tmp.result(tb);
86 const int l=buflen < WDL_SHA1SIZE ? buflen : WDL_SHA1SIZE;
87 memcpy(b,tb,l);
88 buflen-=l;
89 b+=l;