File: neo_rand.c

package info (click to toggle)
clearsilver 0.10.5-1.3
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 3,276 kB
  • sloc: ansic: 24,586; python: 4,233; sh: 2,502; cs: 1,429; ruby: 819; java: 735; makefile: 602; perl: 118; lisp: 34; sql: 21
file content (114 lines) | stat: -rw-r--r-- 1,939 bytes parent folder | download | duplicates (8)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
 * Copyright 2001-2004 Brandon Long
 * All Rights Reserved.
 *
 * ClearSilver Templating System
 *
 * This code is made available under the terms of the ClearSilver License.
 * http://www.clearsilver.net/license.hdf
 *
 */

#include "cs_config.h"

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_rand.h"
#include "ulist.h"

static int RandomInit = 0;

void neo_seed_rand (long int seed)
{
#ifdef HAVE_DRAND48
  srand48(seed);
#elif HAVE_RANDOM
  srandom(seed);
#else
  srand(seed);
#endif
  RandomInit = 1;
}

int neo_rand (int max)
{
  int r;

  if (RandomInit == 0)
  {
    neo_seed_rand (time(NULL));
  }
#ifdef HAVE_DRAND48
  r = drand48() * max;
#elif HAVE_RANDOM
  r = random() * max;
#else
  r = rand() * max;
#endif
  return r;
}

int neo_rand_string (char *s, int max)
{
  int size;
  int x = 0;

  size = neo_rand(max-1);
  for (x = 0; x < size; x++)
  {
    s[x] = (char)(32 + neo_rand(127-32));
    if (s[x] == '/') s[x] = ' ';
  }
  s[x] = '\0';

  return 0;
}

static ULIST *Words = NULL;

int neo_rand_word (char *s, int max)
{
  NEOERR *err;
  int x;
  char *word;

  if (Words == NULL)
  {
    FILE *fp;
    char buf[256];

    err = uListInit(&Words, 40000, 0);
    if (err) 
    {
      nerr_log_error(err);
      return -1;
    }
    fp = fopen ("/usr/dict/words", "r");
    if (fp == NULL) {
      fp = fopen ("/usr/share/dict/words", "r");
      if (fp == NULL) {
        ne_warn("Unable to find dict/words file (looked in /usr/dict/words and /usr/share/dict/words)");
        return -1;
      }
    }
    while (fgets (buf, sizeof(buf), fp) != NULL)
    {
      x = strlen (buf);
      if (buf[x-1] == '\n')
	buf[x-1] = '\0';
      uListAppend(Words, strdup(buf));
    }
    fclose (fp);
  }
  x = neo_rand (uListLength(Words));
  uListGet(Words, x, (void *)&word);
  strncpy (s, word, max);
  s[max-1] = '\0';

  return 0;
}