• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2021 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  * After Public Domain implementations
25  *
26  * https://github.com/svaarala/duktape/tree/master/misc
27  */
28 
29 #include <private-lib-core.h>
30 
rol64(uint64_t x,int k)31 static inline uint64_t rol64(uint64_t x, int k)
32 {
33 	return (x << k) | (x >> (64 - k));
34 }
35 
36 uint64_t
lws_xos(struct lws_xos * xos)37 lws_xos(struct lws_xos *xos)
38 {
39 	uint64_t *s = &xos->s[0];
40 	uint64_t const result = rol64(s[1] * 5, 7) * 9;
41 	uint64_t const c = s[1] << 17;
42 
43 	s[2] ^= s[0];
44 	s[3] ^= s[1];
45 	s[1] ^= s[2];
46 	s[0] ^= s[3];
47 
48 	s[2] ^= c;
49 	s[3] = rol64(s[3], 45);
50 
51 	return result;
52 }
53 
54 static uint64_t
splitmix64(uint64_t * s)55 splitmix64(uint64_t *s)
56 {
57 	uint64_t r = *s;
58 
59 	*s = r + 0x9E3779B97F4A7C15ull;
60 
61 	r = (r ^ (r >> 30)) * 0xBF58476D1CE4E5B9ull;
62 	r = (r ^ (r >> 27)) * 0x94D049BB133111EBull;
63 
64 	return r ^ (r >> 31);
65 }
66 
67 void
lws_xos_init(struct lws_xos * xos,uint64_t seed)68 lws_xos_init(struct lws_xos *xos, uint64_t seed)
69 {
70 	int n;
71 
72 	for (n = 0; n < 4; n++)
73 		xos->s[n] = splitmix64(&seed);
74 }
75 
76 int
lws_xos_percent(struct lws_xos * xos,int percent)77 lws_xos_percent(struct lws_xos *xos, int percent)
78 {
79 	return (int)(lws_xos(xos) % 100) < percent;
80 }
81