Last active
January 15, 2023 18:34
-
-
Save robdelacruz/25d1bc5a7ea72bd86088d2f28f2ba5f9 to your computer and use it in GitHub Desktop.
Perl port of https://gist.github.com/mikelehen/3596a30bd69384624c11 - Firebase style push guids
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
#!/usr/bin/perl | |
use v5.14; | |
use POSIX; | |
use Time::HiRes qw/time gettimeofday usleep/; | |
# Usage: | |
# my $newId = gen_pushid(); | |
# | |
# Ported from: | |
# https://gist.github.com/mikelehen/3596a30bd69384624c11 | |
# ms since epoch | |
sub epochMs { | |
my ($sec, $microSec) = gettimeofday; | |
return int($sec*1000 + $microSec/1000); | |
} | |
sub gen_pushid { | |
state $_pushchars = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; | |
state $_lastPushTime; | |
state @_randIndexes; | |
my $now = epochMs(); | |
if ($now != $_lastPushTime) { | |
# Generate new set of random indexes to pushchars. | |
for (my $i=0; $i < 12; $i++) { | |
$_randIndexes[$i] = int(rand(64)); | |
} | |
} else { | |
# Same time, so just increment previous random index. | |
for (my $i=0; $i < 12; $i++) { | |
$_randIndexes[$i] += 1; | |
if ($_randIndexes[$i] < 64) { | |
last; | |
} | |
$_randIndexes[$i] = 0; # carry inc to next digit | |
} | |
} | |
$_lastPushTime = $now; | |
my @id; | |
# Copy pushchars to @id columns [19..8] (rightmost index to left) | |
for my $idx (@_randIndexes) { | |
unshift @id, substr($_pushchars, $idx, 1); | |
} | |
# Add time-based pushchars to @id columns [7..0] (rightmost index to left) | |
for (my $i=0; $i < 8; $i++) { | |
unshift @id, substr($_pushchars, $now % 64, 1); | |
$now = int($now / 64); | |
} | |
my $sid = join("", @id); | |
return $sid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copy and paste the code in your perl file and call gen_pushid() as a function: