Skip to content

Commit

Permalink
check the length of the Uint8list returned by the custom RNG
Browse files Browse the repository at this point in the history
  • Loading branch information
wph144 authored and daegalus committed Apr 6, 2023
1 parent b1d9daf commit ca2bf53
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions lib/rng.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
import 'dart:math';
import 'dart:typed_data';

// ignore: one_member_abstracts
abstract class RNG {
Uint8List generate();
const RNG();

Uint8List generate() {
final uint8list = generateInternal();
if (uint8list.length != 16) {
throw Exception('The length of the Uint8list returned by the custom RNG must be 16.');
} else {
return uint8list;
}
}

Uint8List generateInternal();
}

/// Math.Random()-based RNG. All platforms, fast, not cryptographically
/// strong. Optional [seed] can be passed on creation.
class MathRNG implements RNG {
class MathRNG extends RNG {
static final _random = Random();
final int seed;

const MathRNG({this.seed = -1});

@override
Uint8List generate() {
Uint8List generateInternal() {
final b = Uint8List(16);
final rand = (seed == -1) ? _random : Random(seed);

Expand All @@ -29,11 +39,11 @@ class MathRNG implements RNG {

/// Crypto-Strong RNG. All platforms, unknown speed, cryptographically strong
/// (theoretically)
class CryptoRNG implements RNG {
class CryptoRNG extends RNG {
static final _secureRandom = Random.secure();

@override
Uint8List generate() {
Uint8List generateInternal() {
final b = Uint8List(16);

for (var i = 0; i < 16; i++) {
Expand All @@ -46,15 +56,15 @@ class CryptoRNG implements RNG {

// LegacyRNG is a wrapper around a legacy RNG function that takes named and
// positional arguments.
class LegacyRNG implements RNG {
class LegacyRNG extends RNG {
final Function _rng;
final Map<Symbol, dynamic> _namedArgs;
final List<dynamic> _positionalArgs;

const LegacyRNG(this._rng, this._namedArgs, this._positionalArgs);

@override
Uint8List generate() {
Uint8List generateInternal() {
return Function.apply(_rng, _positionalArgs, _namedArgs);
}
}

0 comments on commit ca2bf53

Please sign in to comment.