/src/open5gs/lib/asn1c/common/asn_random_fill.c
Line | Count | Source |
1 | | /* |
2 | | * Copyright (c) 2017 Lev Walkin <vlm@lionet.info>. |
3 | | * All rights reserved. |
4 | | * Redistribution and modifications are permitted subject to BSD license. |
5 | | */ |
6 | | #include <asn_internal.h> |
7 | | #include <asn_random_fill.h> |
8 | | #include <constr_TYPE.h> |
9 | | #include <stdlib.h> |
10 | | |
11 | | int |
12 | | asn_random_fill(const struct asn_TYPE_descriptor_s *td, void **struct_ptr, |
13 | 0 | size_t length) { |
14 | |
|
15 | 0 | if(td && td->op->random_fill) { |
16 | 0 | asn_random_fill_result_t res = |
17 | 0 | td->op->random_fill(td, struct_ptr, 0, length); |
18 | 0 | return (res.code == ARFILL_OK) ? 0 : -1; |
19 | 0 | } else { |
20 | 0 | return -1; |
21 | 0 | } |
22 | 0 | } |
23 | | |
24 | | static uintmax_t |
25 | 0 | asn__intmax_range(intmax_t lb, intmax_t ub) { |
26 | 0 | assert(lb <= ub); |
27 | 0 | if((ub < 0) == (lb < 0)) { |
28 | 0 | return ub - lb; |
29 | 0 | } else if(lb < 0) { |
30 | 0 | return 1 + ((uintmax_t)ub + (uintmax_t)-(lb + 1)); |
31 | 0 | } else { |
32 | 0 | assert(!"Unreachable"); |
33 | 0 | return 0; |
34 | 0 | } |
35 | 0 | } |
36 | | |
37 | | intmax_t |
38 | 0 | asn_random_between(intmax_t lb, intmax_t rb) { |
39 | 0 | if(lb == rb) { |
40 | 0 | return lb; |
41 | 0 | } else { |
42 | 0 | const uintmax_t intmax_max = ((~(uintmax_t)0) >> 1); |
43 | 0 | uintmax_t range = asn__intmax_range(lb, rb); |
44 | 0 | uintmax_t value = 0; |
45 | 0 | uintmax_t got_entropy = 0; |
46 | 0 | (void)intmax_max; |
47 | 0 | int max = 0xffffff; |
48 | |
|
49 | | #ifdef __WIN32__ |
50 | | max = RAND_MAX-1; |
51 | | #endif |
52 | |
|
53 | 0 | assert(RAND_MAX > max); /* Seen 7ffffffd! */ |
54 | 0 | assert(range < intmax_max); |
55 | |
|
56 | 0 | for(; got_entropy < range;) { |
57 | 0 | got_entropy = (got_entropy << 24) | max; |
58 | | #ifdef HAVE_RANDOM |
59 | | value = (value << 24) | (random() % max); |
60 | | #else |
61 | 0 | value = (value << 24) | (rand() % max); |
62 | 0 | #endif |
63 | 0 | } |
64 | |
|
65 | 0 | return lb + (intmax_t)(value % (range + 1)); |
66 | 0 | } |
67 | 0 | } |