FNextPushId.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseDatabase/Sources/Utilities/FNextPushId.h"
  17. #import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
  18. static NSString *const PUSH_CHARS =
  19. @"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
  20. @implementation FNextPushId
  21. + (NSString *)get:(NSTimeInterval)currentTime {
  22. static long long lastPushTime = 0;
  23. static int lastRandChars[12];
  24. long long now = (long long)(currentTime * 1000);
  25. BOOL duplicateTime = now == lastPushTime;
  26. lastPushTime = now;
  27. unichar timeStampChars[8];
  28. for (int i = 7; i >= 0; i--) {
  29. timeStampChars[i] = [PUSH_CHARS characterAtIndex:(now % 64)];
  30. now = (long long)floor(now / 64);
  31. }
  32. NSMutableString *id = [[NSMutableString alloc] init];
  33. [id appendString:[NSString stringWithCharacters:timeStampChars length:8]];
  34. if (!duplicateTime) {
  35. for (int i = 0; i < 12; i++) {
  36. lastRandChars[i] = (int)floor(arc4random() % 64);
  37. }
  38. } else {
  39. int i = 0;
  40. for (i = 11; i >= 0 && lastRandChars[i] == 63; i--) {
  41. lastRandChars[i] = 0;
  42. }
  43. lastRandChars[i]++;
  44. }
  45. for (int i = 0; i < 12; i++) {
  46. [id appendFormat:@"%C", [PUSH_CHARS characterAtIndex:lastRandChars[i]]];
  47. }
  48. return [NSString stringWithString:id];
  49. }
  50. @end