summaryrefslogtreecommitdiffstats
path: root/util/src/rand.c
blob: 44057a80d2f5d22795e79551c95eb33576978bdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 * Copyright 2004,2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <axutil_rand.h>
#include <axutil_string.h>
#include <platforms/axutil_platform_auto_sense.h>

#define AXIS2_RAND_MAX 32768

AXIS2_EXTERN int AXIS2_CALL
axutil_rand(
    unsigned int *seedp)
{
    *seedp = *seedp * 1103515245 + 12345;
    return ((unsigned)(*seedp / (2 * AXIS2_RAND_MAX)) % AXIS2_RAND_MAX);
}

AXIS2_EXTERN int AXIS2_CALL
axutil_rand_with_range(
    unsigned int *seedp,
    int start,
    int end)
{
    int rand = -1;
    float range = 0.0;
    if(start < 0 || end <= 0)
        return -1;
    if(start >= AXIS2_RAND_MAX || end > AXIS2_RAND_MAX)
        return -1;
    if(end <= start)
        return -1;

    range = (float)(end - start);
    rand = axutil_rand(seedp);
    rand = start + (int)(range * rand / (AXIS2_RAND_MAX + 1.0));
    return rand;
}

AXIS2_EXTERN unsigned int AXIS2_CALL
axutil_rand_get_seed_value_based_on_time(
    const axutil_env_t * env)
{
    axutil_date_time_t *date = axutil_date_time_create(env);
    unsigned int rand_var = axutil_date_time_get_year(date, env);
    rand_var += axutil_date_time_get_month(date, env);
    rand_var += axutil_date_time_get_day(date, env);
    rand_var += axutil_date_time_get_hour(date, env);
    rand_var += axutil_date_time_get_minute(date, env);
    rand_var += axutil_date_time_get_second(date, env);
    axutil_date_time_free(date, env);
    return rand_var;
}