Skip to content

Instantly share code, notes, and snippets.

@adisesha
Forked from amirh/generate_pushid.dart
Last active September 11, 2020 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adisesha/1bbf29574270d252f283a2fbfa4a0570 to your computer and use it in GitHub Desktop.
Save adisesha/1bbf29574270d252f283a2fbfa4a0570 to your computer and use it in GitHub Desktop.
Dart port of Firebase push ID generator (origin: https://gist.github.com/mikelehen/3596a30bd69384624c11)
import 'dart:math' as math;
//See https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html
//https://gist.github.com/amirh/0e7b480691f7e6506317a7600398124b
//Modified to remove hyphen and underscore to make ids url freindly
const String _kPushChars =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const _pushCharsLength = _kPushChars.length;
class _PushIdGenerator {
int lastPushTime = 0;
final List<int> randomSuffix = new List<int>(12);
final math.Random random = new math.Random.secure();
String next() {
final int now = new DateTime.now().toUtc().millisecondsSinceEpoch;
String id = _toPushIdBase64(now, 8);
if (now != lastPushTime) {
for (int i = 0; i < 12; i += 1) {
randomSuffix[i] = random.nextInt(_pushCharsLength);
}
} else {
int i;
for (i = 11; i >= 0 && randomSuffix[i] == _pushCharsLength - 1; i--)
randomSuffix[i] = 0;
randomSuffix[i] += 1;
}
final String suffixStr = randomSuffix.map((int i) => _kPushChars[i]).join();
lastPushTime = now;
return '$id$suffixStr';
}
String _toPushIdBase64(int value, int numChars) {
List<String> chars = new List<String>(numChars);
for (int i = numChars - 1; i >= 0; i -= 1) {
chars[i] = _kPushChars[value % _pushCharsLength];
value = (value / _pushCharsLength).floor();
}
assert(value == 0);
return chars.join();
}
}
_PushIdGenerator _idGenerator = new _PushIdGenerator();
String generateId() => _idGenerator.next();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment