Skip to content

Instantly share code, notes, and snippets.

@sinuke
Created April 3, 2021 08:54
Show Gist options
  • Save sinuke/1e8ffe14ffa9eb331397c9ee707fc83b to your computer and use it in GitHub Desktop.
Save sinuke/1e8ffe14ffa9eb331397c9ee707fc83b to your computer and use it in GitHub Desktop.
Delphi code for generating Firebase Push IDs
unit Firebase.PushID;
interface
type
TFirebaseBushID = class
private
class var FLastPushTime: Int64;
class var FLastRandChars: array [0 .. 11] of Integer;
public
class function GeneratePushID: string;
end;
implementation
uses System.DateUtils,
System.SysUtils,
System.Math;
{ TFirebaseBushID }
class function TFirebaseBushID.GeneratePushID: string;
var
dublicateTime: Boolean;
nowTime: Int64;
timeStampChars: array [0 .. 7] of Char;
i: Integer;
id: string;
const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
begin
nowTime := System.DateUtils.MilliSecondsBetween(TTimeZone.Local.ToUniversalTime(Now), UnixDateDelta);
dublicateTime := (nowTime = FLastPushTime);
FLastPushTime := nowTime;
id := string.Empty;
for i := 7 downto 0 do
begin
timeStampChars[i] := PUSH_CHARS.Chars[nowTime mod 64];
nowTime := nowTime div 64;
end;
if nowTime <> 0 then
raise Exception.Create('We should have converted the entire timestamp.');
for i := 0 to 7 do
id := id + timeStampChars[i];
if not dublicateTime then
begin
for i := 0 to 11 do
FLastRandChars[i] := System.Math.Floor(Random * 64);
end
else
begin
i := 11;
while (i >= 0) and (FLastRandChars[i] = 63) do
begin
FLastRandChars[i] := 0;
Dec(i);
end;
FLastRandChars[i] := FLastRandChars[i] + 1;
end;
for i := 0 to 11 do
id := id + PUSH_CHARS.Chars[FLastRandChars[i]];
if id.Length <> 20 then
raise Exception.Create('Length should be 20.');
Result := id;
end;
initialization
Randomize;
TFirebaseBushID.FLastPushTime := 0;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment