Skip to content

Instantly share code, notes, and snippets.

@pepijntb
Forked from jfbyers/FireBasePushIdGenerator.java
Last active December 7, 2016 20:04
Show Gist options
  • Save pepijntb/067db689459fd26949dc to your computer and use it in GitHub Desktop.
Save pepijntb/067db689459fd26949dc to your computer and use it in GitHub Desktop.
Port of Firebase Pushid generator in Java. See original at https://gist.github.com/mikelehen/3596a30bd69384624c11#file-generate-pushid-js
package com.firebase.utils;
public class FireBasePushIdGenerator {
static final String PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
static long LAST_PUSH_TIME = 0;
static int[] LAST_RANDOM_CHAR_IDXS= new int[12];
static char[] ID = new char[20];
public static String getFirebaseId() {
long now = System.currentTimeMillis();
boolean duplicateTime = now==LAST_PUSH_TIME;
LAST_PUSH_TIME = now;
if(!duplicateTime) {
for(int i = 7; i >= 0; i--) {
ID[i]=PUSH_CHARS.charAt((int) (now%64));
now = (long) Math.floor(now / 64);
}
}
if(!duplicateTime) {
for (int i = 0; i < 12; i++) {
LAST_RANDOM_CHAR_IDXS[i]=(int) Math.floor(Math.random() * 64);
ID[8+i]=PUSH_CHARS.charAt(LAST_RANDOM_CHAR_IDXS[i]);
}
} else {
int i = 11;
for (; i >= 0 && LAST_RANDOM_CHAR_IDXS[i] == 63; i--) {
LAST_RANDOM_CHAR_IDXS[i]=0;
}
LAST_RANDOM_CHAR_IDXS[i]++;
}
for(int i = 0; i < 12; i++) {
ID[8+i]=PUSH_CHARS.charAt(LAST_RANDOM_CHAR_IDXS[i]);
}
return String.valueOf(ID);
}
}
@speedymovil-interno
Copy link

speedymovil-interno commented Dec 7, 2016

Be careful because you can end up with negative index:

  int i = 11;
            for (; i >= 0 && LAST_RANDOM_CHAR_IDXS[i] == 63; i--) {
                LAST_RANDOM_CHAR_IDXS[i]=0;
            }
            LAST_RANDOM_CHAR_IDXS[i]++;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment