xref: /JGit/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/TestRng.java (revision 5c5f7c6b146b24f2bd4afae1902df85ad6e57ea3)
1 /*
2  * Copyright (C) 2008-2010, Google Inc. and others
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Distribution License v. 1.0 which is available at
6  * https://www.eclipse.org/org/documents/edl-v10.php.
7  *
8  * SPDX-License-Identifier: BSD-3-Clause
9  */
10 
11 package org.eclipse.jgit.junit;
12 
13 /**
14  * Toy RNG to ensure we get predictable numbers during unit tests.
15  */
16 public class TestRng {
17 	private int next;
18 
19 	/**
20 	 * Create a new random number generator, seeded by a string.
21 	 *
22 	 * @param seed
23 	 *            seed to bootstrap, usually this is the test method name.
24 	 */
TestRng(String seed)25 	public TestRng(String seed) {
26 		next = 0;
27 		for (int i = 0; i < seed.length(); i++)
28 			next = next * 11 + seed.charAt(i);
29 	}
30 
31 	/**
32 	 * Get the next {@code cnt} bytes of random data.
33 	 *
34 	 * @param cnt
35 	 *            number of random bytes to produce.
36 	 * @return array of {@code cnt} randomly generated bytes.
37 	 */
nextBytes(int cnt)38 	public byte[] nextBytes(int cnt) {
39 		final byte[] r = new byte[cnt];
40 		for (int i = 0; i < cnt; i++)
41 			r[i] = (byte) nextInt();
42 		return r;
43 	}
44 
45 	/**
46 	 * Next int
47 	 *
48 	 * @return the next random integer.
49 	 */
nextInt()50 	public int nextInt() {
51 		next = next * 1103515245 + 12345;
52 		return next;
53 	}
54 }
55