Forked from jfbyers/FireBasePushIdGenerator.java
Last active
December 7, 2016 20:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be careful because you can end up with negative index: