FNextPushId.m 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 "FNextPushId.h"
  17. #import "FUtilities.h"
  18. static NSString *const PUSH_CHARS = @"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
  19. @implementation FNextPushId
  20. + (NSString *) get:(NSTimeInterval)currentTime {
  21. static long long lastPushTime = 0;
  22. static int lastRandChars[12];
  23. long long now = (long long)(currentTime * 1000);
  24. BOOL duplicateTime = now == lastPushTime;
  25. lastPushTime = now;
  26. unichar timeStampChars[8];
  27. for(int i = 7; i >= 0; i--) {
  28. timeStampChars[i] = [PUSH_CHARS characterAtIndex:(now % 64)];
  29. now = (long long)floor(now / 64);
  30. }
  31. NSMutableString* id = [[NSMutableString alloc] init];
  32. [id appendString:[NSString stringWithCharacters:timeStampChars length:8]];
  33. if(!duplicateTime) {
  34. for(int i = 0; i < 12; i++) {
  35. lastRandChars[i] = (int)floor(arc4random() % 64);
  36. }
  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