File: random.sh

package info (click to toggle)
lizardfs 3.10.4%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,072 kB
  • ctags: 9,596
  • sloc: cpp: 83,275; sh: 8,951; python: 3,872; ansic: 332; pascal: 128; makefile: 60
file content (83 lines) | stat: -rw-r--r-- 2,043 bytes parent folder | download | duplicates (3)
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
parse_si_suffix() {
	if [[ $1 =~ ([0-9]+)(([A-Z]+)?) ]]; then
		local value=${BASH_REMATCH[1]}
		local unit=${BASH_REMATCH[2]}
		local mult=""
		if [[ $unit == "" ]]; then
			echo $value
			return 0
		fi
		case $unit in
			B) mult=1 ;;
			K) mult=1024 ;;
			M) mult=$((1024*1024)) ;;
			G) mult=$((1024*1024*1024)) ;;
			T) mult=$((1024*1024*1024*1024)) ;;
			P) mult=$((1024*1024*1024*1024*1024)) ;;
			E) mult=$((1024*1024*1024*1024*1024*1024)) ;;
			*) return 1 ;;
		esac
		echo $((mult*value))
	else
		return 1
	fi
}

# random <min> <max> -- echoes random number >= min and <= max.
# Examples:
#    random 0 1
#    random 1K 1G
#    random 1 1K
random() {
	local min=$(parse_si_suffix $1)
	local max=$(parse_si_suffix $2)
	shuf -n 1 --input-range=$min-$max
}

# unique_file [<suffix>] -- generates an unique string
# files created by this function are automatically removed at the end of a test
unique_file() {
	local suffix=""
	if (( $# >= 1 )); then
		suffix="_$1"
	fi
	echo "temp_$(date +%s.%N)_$$$suffix"
}

# pseudorandom_init [<seed>] -- sets a seed (default or specified) for pseudorandom generator
pseudorandom_init() {
	pseudorandom_seed_file_="$TEMP_DIR/$(unique_file pseudorandom_seed)"

	if (( $# >= 1 )); then
		local seed=$1
	else
		local seed=115249 # some prime number
	fi
	echo $seed > "$pseudorandom_seed_file_"
}

# pseudo random number generator with glibc algorithm (drawing bits 0..30)
prng() {
	if [[ ! -e "$pseudorandom_seed_file_" ]]; then
		return 1
	fi

	local seed=$(cat "$pseudorandom_seed_file_")
	seed=$(( (1103515245 * seed + 12345) % 2147483648 ))
	echo $seed | tee "$pseudorandom_seed_file_"
}

# pseudorandom <min> <max> -- echoes random number >= min and <= max up to 2^62
# Examples:
#    pseudorandom 0 1
#    pseudorandom 1K 1G
#    pseudorandom 1 1K
pseudorandom() {
	local min=$(parse_si_suffix $1)
	local max=$(parse_si_suffix $2)
	local shift=2147483648 # 2^31
	local pass1=$(prng)
	local pass2=$(( $shift * $(prng) ))
	local result=$(( min + (pass1 + pass2) % (max - min + 1) ))
	echo $result
}