FUtilities.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 <FirebaseCore/FIRLogger.h>
  17. #import "FUtilities.h"
  18. #import "FStringUtilities.h"
  19. #import "FConstants.h"
  20. #import "FAtomicNumber.h"
  21. #define ARC4RANDOM_MAX 0x100000000
  22. #define INTEGER_32_MIN (-2147483648)
  23. #define INTEGER_32_MAX 2147483647
  24. #pragma mark -
  25. #pragma mark C functions
  26. FIRLoggerService kFIRLoggerDatabase = @"[Firebase/Database]";
  27. static FLogLevel logLevel = FLogLevelInfo; // Default log level is info
  28. static NSMutableDictionary* options = nil;
  29. BOOL FFIsLoggingEnabled(FLogLevel level) {
  30. return level >= logLevel;
  31. }
  32. void firebaseJobsTroll(void) {
  33. FFLog(@"I-RDB095001", @"password super secret; JFK conspiracy; Hello there! Having fun digging through Firebase? We're always hiring! jobs@firebase.com");
  34. }
  35. #pragma mark -
  36. #pragma mark Private property and singleton specification
  37. @interface FUtilities() {
  38. }
  39. @property (nonatomic, strong) FAtomicNumber* localUid;
  40. + (FUtilities*)singleton;
  41. @end
  42. @implementation FUtilities
  43. @synthesize localUid;
  44. - (id)init
  45. {
  46. self = [super init];
  47. if (self) {
  48. self.localUid = [[FAtomicNumber alloc] init];
  49. }
  50. return self;
  51. }
  52. // TODO: We really want to be able to set the log level
  53. + (void) setLoggingEnabled:(BOOL)enabled {
  54. logLevel = enabled ? FLogLevelDebug : FLogLevelInfo;
  55. }
  56. + (BOOL) getLoggingEnabled {
  57. return logLevel == FLogLevelDebug;
  58. }
  59. + (FUtilities*) singleton
  60. {
  61. static dispatch_once_t pred = 0;
  62. __strong static id _sharedObject = nil;
  63. dispatch_once(&pred, ^{
  64. _sharedObject = [[self alloc] init]; // or some other init method
  65. });
  66. return _sharedObject;
  67. }
  68. // Refactor as a category of NSString
  69. + (NSArray *) splitString:(NSString *) str intoMaxSize:(const unsigned int) size {
  70. if(str.length <= size) {
  71. return [NSArray arrayWithObject:str];
  72. }
  73. NSMutableArray* dataSegs = [[NSMutableArray alloc] init];
  74. for(int c = 0; c < str.length; c += size) {
  75. if (c + size > str.length) {
  76. int rangeStart = c;
  77. unsigned long rangeLength = size - ((c + size) - str.length);
  78. [dataSegs addObject:[str substringWithRange:NSMakeRange(rangeStart, rangeLength)]];
  79. }
  80. else {
  81. int rangeStart = c;
  82. int rangeLength = size;
  83. [dataSegs addObject:[str substringWithRange:NSMakeRange(rangeStart, rangeLength)]];
  84. }
  85. }
  86. return dataSegs;
  87. }
  88. + (NSNumber *) LUIDGenerator {
  89. FUtilities* f = [FUtilities singleton];
  90. return [f.localUid getAndIncrement];
  91. }
  92. + (NSString *) decodePath:(NSString *)pathString {
  93. NSMutableArray* decodedPieces = [[NSMutableArray alloc] init];
  94. NSArray* pieces = [pathString componentsSeparatedByString:@"/"];
  95. for (NSString* piece in pieces) {
  96. if (piece.length > 0) {
  97. [decodedPieces addObject:[FStringUtilities urlDecoded:piece]];
  98. }
  99. }
  100. return [NSString stringWithFormat:@"/%@", [decodedPieces componentsJoinedByString:@"/"]];
  101. }
  102. + (FParsedUrl *) parseUrl:(NSString *)url {
  103. NSString* original = url;
  104. //NSURL* n = [[NSURL alloc] initWithString:url]
  105. NSString* host;
  106. NSString* namespace;
  107. bool secure;
  108. NSString* scheme = nil;
  109. FPath* path = nil;
  110. NSRange colonIndex = [url rangeOfString:@"//"];
  111. if (colonIndex.location != NSNotFound) {
  112. scheme = [url substringToIndex:colonIndex.location - 1];
  113. url = [url substringFromIndex:colonIndex.location + 2];
  114. }
  115. NSInteger slashIndex = [url rangeOfString:@"/"].location;
  116. if (slashIndex == NSNotFound) {
  117. slashIndex = url.length;
  118. }
  119. host = [[url substringToIndex:slashIndex] lowercaseString];
  120. if (slashIndex >= url.length) {
  121. url = @"";
  122. } else {
  123. url = [url substringFromIndex:slashIndex + 1];
  124. }
  125. NSArray *parts = [host componentsSeparatedByString:@"."];
  126. if([parts count] == 3) {
  127. NSInteger colonIndex = [[parts objectAtIndex:2] rangeOfString:@":"].location;
  128. if (colonIndex != NSNotFound) {
  129. // we have a port, use the provided scheme
  130. secure = [scheme isEqualToString:@"https"];
  131. } else {
  132. secure = YES;
  133. }
  134. namespace = [[parts objectAtIndex:0] lowercaseString];
  135. NSString* pathString = [self decodePath:[NSString stringWithFormat:@"/%@", url]];
  136. path = [[FPath alloc] initWith:pathString];
  137. }
  138. else {
  139. [NSException raise:@"No Firebase database specified." format:@"No Firebase database found for input: %@", url];
  140. }
  141. FRepoInfo* repoInfo = [[FRepoInfo alloc] initWithHost:host isSecure:secure withNamespace:namespace];
  142. FFLog(@"I-RDB095002", @"---> Parsed (%@) to: (%@,%@); ns=(%@); path=(%@)", original, [repoInfo description], [repoInfo connectionURL], repoInfo.namespace, [path description]);
  143. FParsedUrl* parsedUrl = [[FParsedUrl alloc] init];
  144. parsedUrl.repoInfo = repoInfo;
  145. parsedUrl.path = path;
  146. return parsedUrl;
  147. }
  148. /*
  149. case str: JString => priString + "string:" + str.s;
  150. case bool: JBool => priString + "boolean:" + bool.value;
  151. case double: JDouble => priString + "number:" + double.num;
  152. case int: JInt => priString + "number:" + int.num;
  153. case _ => {
  154. error("Leaf node has value '" + data.value + "' of invalid type '" + data.value.getClass.toString + "'");
  155. "";
  156. }
  157. */
  158. + (NSString *) getJavascriptType:(id)obj {
  159. if ([obj isKindOfClass:[NSDictionary class]]) {
  160. return kJavaScriptObject;
  161. } else if([obj isKindOfClass:[NSString class]]) {
  162. return kJavaScriptString;
  163. }
  164. else if ([obj isKindOfClass:[NSNumber class]]) {
  165. // We used to just compare to @encode(BOOL) as suggested at
  166. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber, but on arm64, @encode(BOOL) returns "B"
  167. // instead of "c" even though objCType still returns 'c' (signed char). So check both.
  168. if(strcmp([obj objCType], @encode(BOOL)) == 0 ||
  169. strcmp([obj objCType], @encode(signed char)) == 0) {
  170. return kJavaScriptBoolean;
  171. }
  172. else {
  173. return kJavaScriptNumber;
  174. }
  175. }
  176. else {
  177. return kJavaScriptNull;
  178. }
  179. }
  180. + (NSError *) errorForStatus:(NSString *)status andReason:(NSString *)reason {
  181. static dispatch_once_t pred = 0;
  182. __strong static NSDictionary* errorMap = nil;
  183. __strong static NSDictionary* errorCodes = nil;
  184. dispatch_once(&pred, ^{
  185. errorMap = @{
  186. @"permission_denied": @"Permission Denied",
  187. @"unavailable": @"Service is unavailable",
  188. kFErrorWriteCanceled: @"Write cancelled by user"
  189. };
  190. errorCodes = @{
  191. @"permission_denied": @1,
  192. @"unavailable": @2,
  193. kFErrorWriteCanceled: @3
  194. };
  195. });
  196. if ([status isEqualToString:kFWPResponseForActionStatusOk]) {
  197. return nil;
  198. } else {
  199. NSInteger code;
  200. NSString* desc = nil;
  201. if (reason) {
  202. desc = reason;
  203. } else if ([errorMap objectForKey:status] != nil) {
  204. desc = [errorMap objectForKey:status];
  205. } else {
  206. desc = status;
  207. }
  208. if ([errorCodes objectForKey:status] != nil) {
  209. NSNumber* num = [errorCodes objectForKey:status];
  210. code = [num integerValue];
  211. } else {
  212. // XXX what to do here?
  213. code = 9999;
  214. }
  215. return [[NSError alloc] initWithDomain:kFErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey: desc}];
  216. }
  217. }
  218. + (NSNumber *) intForString:(NSString *)string {
  219. static NSCharacterSet *notDigits = nil;
  220. if (!notDigits) {
  221. notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  222. }
  223. if ([string rangeOfCharacterFromSet:notDigits].length == 0) {
  224. NSInteger num;
  225. NSScanner* scanner = [NSScanner scannerWithString:string];
  226. if ([scanner scanInteger:&num]) {
  227. return [NSNumber numberWithInteger:num];
  228. }
  229. }
  230. return nil;
  231. }
  232. + (NSString *) ieee754StringForNumber:(NSNumber *)val {
  233. double d = [val doubleValue];
  234. NSData* data = [NSData dataWithBytes:&d length:sizeof(double)];
  235. NSMutableString* str = [[NSMutableString alloc] init];
  236. const unsigned char* buffer = (const unsigned char*)[data bytes];
  237. for (int i = 0; i < data.length; i++) {
  238. unsigned char byte = buffer[7 - i];
  239. [str appendFormat:@"%02x", byte];
  240. }
  241. return str;
  242. }
  243. static inline BOOL tryParseStringToInt(__unsafe_unretained NSString* str, NSInteger* integer) {
  244. // First do some cheap checks (NOTE: The below checks are significantly faster than an equivalent regex :-( ).
  245. NSUInteger length = str.length;
  246. if (length > 11 || length == 0) {
  247. return NO;
  248. }
  249. long long value = 0;
  250. BOOL negative = NO;
  251. NSUInteger i = 0;
  252. if ([str characterAtIndex:0] == '-') {
  253. if (length == 1) {
  254. return NO;
  255. }
  256. negative = YES;
  257. i = 1;
  258. }
  259. for(; i < length; i++) {
  260. unichar c = [str characterAtIndex:i];
  261. // Must be a digit, or '-' if it's the first char.
  262. if (c < '0' || c > '9') {
  263. return NO;
  264. } else {
  265. int charValue = c - '0';
  266. value = value*10 + charValue;
  267. }
  268. }
  269. value = (negative) ? -value : value;
  270. if (value < INTEGER_32_MIN || value > INTEGER_32_MAX) {
  271. return NO;
  272. } else {
  273. *integer = (NSInteger)value;
  274. return YES;
  275. }
  276. }
  277. + (NSString *) maxName {
  278. static dispatch_once_t once;
  279. static NSString *maxName;
  280. dispatch_once(&once, ^{
  281. maxName = [[NSString alloc] initWithFormat:@"[MAX_NAME]"];
  282. });
  283. return maxName;
  284. }
  285. + (NSString *) minName {
  286. static dispatch_once_t once;
  287. static NSString *minName;
  288. dispatch_once(&once, ^{
  289. minName = [[NSString alloc] initWithFormat:@"[MIN_NAME]"];
  290. });
  291. return minName;
  292. }
  293. + (NSComparisonResult) compareKey:(NSString *)a toKey:(NSString *)b {
  294. if (a == b) {
  295. return NSOrderedSame;
  296. } else if (a == [FUtilities minName] || b == [FUtilities maxName]) {
  297. return NSOrderedAscending;
  298. } else if (b == [FUtilities minName] || a == [FUtilities maxName]) {
  299. return NSOrderedDescending;
  300. } else {
  301. NSInteger aAsInt, bAsInt;
  302. if (tryParseStringToInt(a, &aAsInt)) {
  303. if (tryParseStringToInt(b, &bAsInt)) {
  304. if (aAsInt > bAsInt) {
  305. return NSOrderedDescending;
  306. } else if (aAsInt < bAsInt) {
  307. return NSOrderedAscending;
  308. } else if (a.length > b.length) {
  309. return NSOrderedDescending;
  310. } else if (a.length < b.length) {
  311. return NSOrderedAscending;
  312. } else {
  313. return NSOrderedSame;
  314. }
  315. } else {
  316. return (NSComparisonResult) NSOrderedAscending;
  317. }
  318. } else if (tryParseStringToInt(b, &bAsInt)) {
  319. return (NSComparisonResult) NSOrderedDescending;
  320. } else {
  321. // Perform literal character by character search to prevent a > b && b > a issues.
  322. // Note that calling -(NSString *)decomposedStringWithCanonicalMapping also works.
  323. return [a compare:b options:NSLiteralSearch];
  324. }
  325. }
  326. }
  327. + (NSComparator) keyComparator {
  328. return ^NSComparisonResult(__unsafe_unretained NSString *a, __unsafe_unretained NSString *b) {
  329. return [FUtilities compareKey:a toKey:b];
  330. };
  331. }
  332. + (NSComparator) stringComparator {
  333. return ^NSComparisonResult(__unsafe_unretained NSString *a, __unsafe_unretained NSString *b) {
  334. return [a compare:b];
  335. };
  336. }
  337. + (double) randomDouble {
  338. return ((double) arc4random() / ARC4RANDOM_MAX);
  339. }
  340. @end