aboutsummaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/TestRng.java
blob: e7fe48845bfb1e4a5c06a99971f043249ba271ad (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
/*
 * Copyright (C) 2008-2010, Google Inc. and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Distribution License v. 1.0 which is available at
 * https://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

package org.eclipse.jgit.junit;

/**
 * Toy RNG to ensure we get predictable numbers during unit tests.
 */
public class TestRng {
	private int next;

	/**
	 * Create a new random number generator, seeded by a string.
	 *
	 * @param seed
	 *            seed to bootstrap, usually this is the test method name.
	 */
	public TestRng(String seed) {
		next = 0;
		for (int i = 0; i < seed.length(); i++)
			next = next * 11 + seed.charAt(i);
	}

	/**
	 * Get the next {@code cnt} bytes of random data.
	 *
	 * @param cnt
	 *            number of random bytes to produce.
	 * @return array of {@code cnt} randomly generated bytes.
	 */
	public byte[] nextBytes(int cnt) {
		final byte[] r = new byte[cnt];
		for (int i = 0; i < cnt; i++)
			r[i] = (byte) nextInt();
		return r;
	}

	/**
	 * Next int
	 *
	 * @return the next random integer.
	 */
	public int nextInt() {
		next = next * 1103515245 + 12345;
		return next;
	}
}