Util: Fast check for random nextInt(1) and nextLong(1)

Document differences from Java's random for n=0
Entropy harvester cleanups, we're not going to add a factory as jrandom implied.
This commit is contained in:
zzz
2022-11-26 09:36:30 -05:00
parent cb5be9530a
commit dfe36b64a5
2 changed files with 12 additions and 10 deletions

View File

@@ -78,10 +78,14 @@ public class FortunaRandomSource extends RandomSource implements EntropyHarveste
* Ok, so we're going to have it return between 0 and n (including 0, excluding n), since
* thats what it has been used for.
*
* Unlike Java's Random, which throws IAE, this returns 0 if n is 0.
*
* @param n non-negative
* @throws IllegalArgumentException if n is negative
*/
@Override
public int nextInt(int n) {
if (n == 0) return 0;
if (n == 1 || n == 0) return 0;
int rv = signedNextInt(n);
if (rv < 0)
rv = 0 - rv;
@@ -134,10 +138,15 @@ public class FortunaRandomSource extends RandomSource implements EntropyHarveste
/**
* Like the modified nextInt, nextLong(n) returns a random number from 0 through n,
* including 0, excluding n.
*
* Unlike Java's Random, which throws IAE, this returns 0 if n is 0.
*
* @param n non-negative
* @throws IllegalArgumentException if n is negative
*/
@Override
public long nextLong(long n) {
if (n == 0) return 0;
if (n == 1 || n == 0) return 0;
long rv = nextLong();
if (rv < 0)
rv = 0 - rv;
@@ -260,9 +269,6 @@ public class FortunaRandomSource extends RandomSource implements EntropyHarveste
return (int)rv;
}
@Override
public EntropyHarvester harvester() { return this; }
/** reseed the fortuna */
@Override
public void feedEntropy(String source, long data, int bitoffset, int bits) {

View File

@@ -27,7 +27,6 @@ import net.i2p.crypto.EntropyHarvester;
public class RandomSource extends SecureRandom implements EntropyHarvester {
private static final long serialVersionUID = 1L;
private final EntropyHarvester _entropyHarvester;
protected transient final I2PAppContext _context;
/**
@@ -39,9 +38,6 @@ public class RandomSource extends SecureRandom implements EntropyHarvester {
public RandomSource(I2PAppContext context) {
super();
_context = context;
// when we replace to have hooks for fortuna (etc), replace with
// a factory (or just a factory method)
_entropyHarvester = this;
}
/**
@@ -113,7 +109,7 @@ public class RandomSource extends SecureRandom implements EntropyHarvester {
}
}
public EntropyHarvester harvester() { return _entropyHarvester; }
public EntropyHarvester harvester() { return this; }
public void feedEntropy(String source, long data, int bitoffset, int bits) {
if (bitoffset == 0)