/
Foundation+CoreCode.m
2384 lines (1862 loc) · 63 KB
/
Foundation+CoreCode.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Foundation+CoreCode.m
// CoreLib
//
// Created by CoreCode on 15.03.12.
/* Copyright (c) 2016 CoreCode
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitationthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import "Foundation+CoreCode.h"
#if __has_feature(modules)
#ifdef USE_SECURITY
#include <CommonCrypto/CommonDigest.h>
#endif
@import ObjectiveC.runtime;
#else
#ifdef USE_SECURITY
#include <CommonCrypto/CommonDigest.h>
#endif
#import <objc/runtime.h>
#endif
#ifdef USE_SNAPPY
#import <snappy/snappy-c.h>
#endif
#if __has_feature(modules)
@import Darwin.POSIX.sys.stat;
#else
#include <sys/stat.h>
#endif
CONST_KEY(CoreCodeAssociatedValue)
@implementation NSArray (CoreCode)
@dynamic mutableObject, empty, set, reverseArray, string, path, sorted, XMLData, flattenedArray, literalString;
#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
@dynamic orderedSet;
#endif
- (NSString *)literalString
{
NSMutableString *tmp = [NSMutableString stringWithString:@"@["];
for (id obj in self)
[tmp appendFormat:@"%@, ", [obj literalString]];
[tmp replaceCharactersInRange:NSMakeRange(tmp.length-2, 2) // replace trailing ', '
withString:@"]"]; // with terminating ']'
return tmp;
}
- (NSArray *)sorted
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wselector"
return [self sortedArrayUsingSelector:@selector(compare:)];
#pragma clang diagnostic pop
}
#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
@dynamic JSONData;
- (NSData *)JSONData
{
NSError *err;
NSData *data = [NSJSONSerialization dataWithJSONObject:self options:(NSJSONWritingOptions)0 error:&err];
if (!data || err)
{
asl_NSLog(ASL_LEVEL_ERR, @"Error: JSON write fails! input %@ data %@ err %@", self, data, err);
return nil;
}
return data;
}
#endif
- (NSData *)XMLData
{
NSError *err;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:self
format:NSPropertyListXMLFormat_v1_0
options:(NSPropertyListWriteOptions)0
error:&err];
if (!data || err)
{
asl_NSLog(ASL_LEVEL_ERR, @"Error: XML write fails! input %@ data %@ err %@", self, data, err);
return nil;
}
return data;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-statement-expression"
- (CCIntRange2D)calculateExtentsOfPoints:(ObjectInPointOutBlock)block
{
CCIntRange2D range = {{INT_MAX, INT_MAX}, {INT_MIN, INT_MIN}, {-1, -1}};
if (self.count)
{
for (NSObject *o in self)
{
CCIntPoint p = block(o);
range.max.x = MAX(range.max.x, p.x);
range.max.y = MAX(range.max.y, p.y);
range.min.x = MIN(range.min.x, p.x);
range.min.y = MIN(range.min.y, p.y);
}
range.length.x = range.max.x - range.min.x;
range.length.y = range.max.y - range.min.y;
}
return range;
}
- (CCIntRange1D)calculateExtentsOfValues:(ObjectInIntOutBlock)block
{
CCIntRange1D range = {INT_MAX, INT_MIN, -1};
if (self.count)
{
for (NSObject *o in self)
{
int p = block(o);
range.min = MIN(range.min, p);
range.max = MAX(range.max, p);
}
range.length = range.max - range.min;
}
return range;
}
#pragma clang diagnostic pop
+ (void)_addArrayContents:(NSArray *)array toArray:(NSMutableArray *)newArray
{
for (id object in array)
{
if ([object isKindOfClass:[NSArray class]])
[NSArray _addArrayContents:object toArray:newArray];
else
[newArray addObject:object];
}
}
- (NSArray *)flattenedArray
{
NSMutableArray *tmp = [NSMutableArray array];
[NSArray _addArrayContents:self toArray:tmp];
return tmp.immutableObject;
}
- (NSString *)string
{
NSString *ret = @"";
for (NSString *str in self)
ret = [ret stringByAppendingString:str];
return ret;
}
- (NSString *)path
{
NSString *ret = @"";
for (NSString *str in self)
ret = [ret stringByAppendingPathComponent:str];
return ret;
}
- (BOOL)contains:(id)object
{
return [self indexOfObject:object] != NSNotFound;
}
- (NSArray *)reverseArray
{
return [[self reverseObjectEnumerator] allObjects];
}
#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
- (NSOrderedSet *)orderedSet
{
return [NSOrderedSet orderedSetWithArray:self];
}
#endif
- (NSSet *)set
{
return [NSSet setWithArray:self];
}
- (NSArray *)arrayByAddingNewObject:(id)anObject
{
if ([self indexOfObject:anObject] == NSNotFound)
return [self arrayByAddingObject:anObject];
else
return self;
}
- (NSArray *)arrayByRemovingObjectIdenticalTo:(id)anObject
{
NSMutableArray *array = [NSMutableArray arrayWithArray:self];
[array removeObjectIdenticalTo:anObject];
return [NSArray arrayWithArray:array];
}
- (NSArray *)arrayByRemovingObjectsIdenticalTo:(NSArray *)objects
{
NSMutableArray *array = [NSMutableArray arrayWithArray:self];
for (id obj in objects)
[array removeObjectIdenticalTo:obj];
return [NSArray arrayWithArray:array];
}
- (NSArray *)arrayByRemovingObjectsAtIndexes:(NSIndexSet *)indexSet
{
NSMutableArray *array = [NSMutableArray arrayWithArray:self];
[array removeObjectsAtIndexes:indexSet];
return [NSArray arrayWithArray:array];
}
- (NSArray *)arrayByRemovingObjectAtIndex:(NSUInteger)index
{
NSMutableArray *array = [NSMutableArray arrayWithArray:self];
[array removeObjectAtIndex:index];
return [NSArray arrayWithArray:array];
}
- (NSArray *)arrayByReplacingObject:(id)anObject withObject:(id)newObject
{
NSMutableArray *mut = self.mutableObject;
mut[[mut indexOfObject:anObject]] = newObject;
return mut.immutableObject;
}
- (id)safeObjectAtIndex:(NSUInteger)index
{
if ([self count] > index)
return self[index];
else
return nil;
}
- (NSString *)safeStringAtIndex:(NSUInteger)index
{
if ([self count] > index)
return self[index];
else
return @"";
}
- (BOOL)containsDictionaryWithKey:(NSString *)key equalTo:(NSString *)value
{
for (NSDictionary *dict in self)
if ([[dict valueForKey:key] isEqual:value])
return TRUE;
return FALSE;
}
- (NSArray *)sortedArrayByKey:(NSString *)key
{
return [self sortedArrayByKey:key ascending:YES];
}
- (NSArray *)sortedArrayByKey:(NSString *)key ascending:(BOOL)ascending
{
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:key ascending:ascending];
#if ! __has_feature(objc_arc)
[sd autorelease];
#endif
return [self sortedArrayUsingDescriptors:@[sd]];
}
- (NSArray *)subarrayFromIndex:(NSUInteger)location
{
return [self subarrayWithRange:NSMakeRange(location, self.count-location)];
}
- (NSArray *)subarrayToIndex:(NSUInteger)location
{
return [self subarrayWithRange:NSMakeRange(0, self.count-location-1)];
}
- (NSMutableArray *)mutableObject
{
return [NSMutableArray arrayWithArray:self];
}
- (BOOL)empty
{
return [self count] == 0;
}
- (NSArray *)mapped:(ObjectInOutBlock)block
{
NSMutableArray *resultArray = [NSMutableArray new];
for (id object in self)
{
id result = block(object);
if (result)
[resultArray addObject:result];
}
#if ! __has_feature(objc_arc)
[resultArray autorelease];
#endif
return [NSArray arrayWithArray:resultArray];
}
- (NSInteger)reduce:(ObjectInIntOutBlock)block
{
NSInteger value = 0;
for (id object in self)
value += block(object);
return value;
}
- (NSArray *)filtered:(BOOL (^)(id input))block
{
NSMutableArray *resultArray = [NSMutableArray new];
for (id object in self)
if (block(object))
[resultArray addObject:object];
#if ! __has_feature(objc_arc)
[resultArray autorelease];
#endif
return [NSArray arrayWithArray:resultArray];
}
- (void)apply:(ObjectInBlock)block // enumerateObjectsUsingBlock:
{
for (id object in self)
block(object);
}
// forwards for less typing
- (NSString *)joined:(NSString *)sep // componentsJoinedByString:
{
return [self componentsJoinedByString:sep];
}
- (NSArray *)filteredUsingPredicateString:(NSString *)format, ...
{
va_list args;
va_start(args, format);
NSPredicate *pred = [NSPredicate predicateWithFormat:format arguments:args];
va_end(args);
return [self filteredArrayUsingPredicate:pred];
}
#if defined(TARGET_OS_MAC) && TARGET_OS_MAC && !TARGET_OS_IPHONE
- (NSString *)runAsTask
{
return [self runAsTaskWithTerminationStatus:NULL];
}
- (NSString *)runAsTaskWithTerminationStatus:(NSInteger *)terminationStatus
{
NSTask *task = [NSTask new];
NSPipe *taskPipe = [NSPipe pipe];
NSFileHandle *file = [taskPipe fileHandleForReading];
[task setLaunchPath:self[0]];
[task setStandardOutput:taskPipe];
[task setStandardError:taskPipe];
[task setArguments:[self subarrayWithRange:NSMakeRange(1, self.count-1)]];
@try
{
[task launch];
}
@catch (NSException *)
{
return nil;
}
NSData *data = [file readDataToEndOfFile];
[task waitUntilExit];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (terminationStatus)
(*terminationStatus) = [task terminationStatus];
#if ! __has_feature(objc_arc)
[task release];
[string autorelease];
#endif
return string;
}
#endif
@end
@implementation NSMutableArray (CoreCode)
@dynamic immutableObject;
- (void)moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex
{
id object = self[fromIndex];
[self removeObjectAtIndex:fromIndex];
if (toIndex < self.count)
[self insertObject:object atIndex:toIndex];
else
[self addObject:object];
}
- (void)removeObjectPassingTest:(ObjectInIntOutBlock)block
{
NSUInteger idx = [self indexOfObjectPassingTest:^BOOL(id obj, NSUInteger i, BOOL *s)
{
int res = block(obj);
return (BOOL)res;
}];
if (idx != NSNotFound)
[self removeObjectAtIndex:idx];
}
- (NSArray *)immutableObject
{
return [NSArray arrayWithArray:self];
}
- (void)addNewObject:(id)anObject
{
if (anObject && [self indexOfObject:anObject] == NSNotFound)
[self addObject:anObject];
}
- (void)addObjectSafely:(id)anObject
{
if (anObject)
[self addObject:anObject];
}
- (void)map:(ObjectInOutBlock)block
{
for (NSUInteger i = 0; i < [self count]; i++)
{
id result = block(self[i]);
self[i] = result;
}
}
- (void)filter:(ObjectInIntOutBlock)block
{
NSMutableIndexSet *indices = [NSMutableIndexSet new];
for (NSUInteger i = 0; i < [self count]; i++)
{
int result = block(self[i]);
if (!result)
[indices addIndex:i];
}
[self removeObjectsAtIndexes:indices];
#if ! __has_feature(objc_arc)
[indices release];
#endif
}
- (void)filterUsingPredicateString:(NSString *)format, ...
{
va_list args;
va_start(args, format);
NSPredicate *pred = [NSPredicate predicateWithFormat:format arguments:args];
va_end(args);
[self filterUsingPredicate:pred];
}
- (void)removeFirstObject
{
[self removeObjectAtIndex:0];
}
@end
@implementation NSString (CoreCode)
@dynamic words, lines, trimmedOfWhitespace, trimmedOfWhitespaceAndNewlines, URL, fileURL, download, resourceURL, resourcePath, localized, defaultObject, defaultString, defaultInt, defaultFloat, defaultURL, dirContents, dirContentsRecursive, dirContentsAbsolute, dirContentsRecursiveAbsolute, fileExists, uniqueFile, expanded, defaultArray, defaultDict, isWriteablePath, fileSize, directorySize, contents, dataFromHexString, unescaped, escaped, namedImage, isIntegerNumber, isIntegerNumberOnly, isFloatNumber, data, firstCharacter, lastCharacter, fullRange, stringByResolvingSymlinksInPathFixed, literalString, isNumber;
#if defined(TARGET_OS_MAC) && TARGET_OS_MAC && !TARGET_OS_IPHONE
@dynamic fileIsAlias, fileAliasTarget, fileIsRestricted;
#endif
#ifdef USE_SECURITY
@dynamic SHA1;
#endif
#if defined(TARGET_OS_MAC) && TARGET_OS_MAC && !TARGET_OS_IPHONE
- (NSImage *)namedImage
{
NSImage *image = [NSImage imageNamed:self];
return image;
}
#else
- (UIImage *)namedImage
{
UIImage *image = [UIImage imageNamed:self];
return image;
}
#endif
#if defined(TARGET_OS_MAC) && TARGET_OS_MAC && !TARGET_OS_IPHONE
- (BOOL)fileIsRestricted
{
struct stat info;
lstat(self.UTF8String, &info);
return (info.st_flags & SF_RESTRICTED) > 0;
}
- (BOOL)fileIsAlias
{
NSURL *url = [NSURL fileURLWithPath:self];
CFURLRef cfurl = (BRIDGE CFURLRef) url;
CFBooleanRef aliasBool = kCFBooleanFalse;
Boolean success = CFURLCopyResourcePropertyForKey(cfurl, kCFURLIsAliasFileKey, &aliasBool, NULL);
Boolean alias = CFBooleanGetValue(aliasBool);
return alias && success;
}
- (NSString *)stringByResolvingSymlinksInPathFixed
{
NSString *ret = [self stringByResolvingSymlinksInPath];
for (NSString *exception in @[@"/etc/", @"/tmp/", @"/var/"])
{
if ([ret hasPrefix:exception])
{
NSString *fixed = [@"/private" stringByAppendingPathComponent:ret];
return fixed;
}
}
return ret;
}
- (NSString *)fileAliasTarget
{
CFErrorRef *err = NULL;
CFDataRef bookmark = CFURLCreateBookmarkDataFromFile(NULL, (BRIDGE CFURLRef)self.fileURL, err);
if (bookmark == nil)
return nil;
CFURLRef url = CFURLCreateByResolvingBookmarkData (NULL, bookmark, kCFBookmarkResolutionWithoutUIMask, NULL, NULL, NULL, err);
__autoreleasing NSURL *nurl = [(BRIDGE NSURL *)url copy];
CFRelease(bookmark);
CFRelease(url);
#if !__has_feature(objc_arc)
[nurl autorelease];
#endif
return [nurl path];
}
- (CGSize)sizeUsingFont:(NSFont *)font maxWidth:(CGFloat)maxWidth
{
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:self];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(maxWidth, DBL_MAX)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage beginEditing];
[textStorage setAttributes:@{NSFontAttributeName: font} range:NSMakeRange(0, [self length])];
[textStorage endEditing];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
NSRect r = [layoutManager usedRectForTextContainer:textContainer];
#if !__has_feature(objc_arc)
[textStorage release];
[layoutManager release];
[textContainer release];
#endif
return r.size;
}
#endif
- (NSString *)literalString
{
return makeString(@"@\"%@\"", self);
}
- (NSRange)fullRange
{
return NSMakeRange(0, self.length);
}
- (unichar)firstCharacter
{
if (self.length)
return [self characterAtIndex:0];
return 0;
}
- (unichar)lastCharacter
{
NSUInteger len = self.length;
if (len)
return [self characterAtIndex:len-1];
return 0;
}
- (unsigned long long)fileSize
{
NSDictionary *attr = [fileManager attributesOfItemAtPath:self error:NULL];
if (!attr) return 0;
return [attr[NSFileSize] unsignedLongLongValue];
}
- (unsigned long long)directorySize
{
unsigned long long size = 0;
for (NSString *file in self.dirContentsRecursiveAbsolute)
{
NSDictionary *attr = [fileManager attributesOfItemAtPath:file error:NULL];
if (attr && !([attr[NSFileType] isEqualToString:NSFileTypeDirectory]))
size += [attr[NSFileSize] unsignedLongLongValue];
}
return size;
}
- (BOOL)isIntegerNumber
{
return [self rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound;
}
- (BOOL)isNumber
{
if (!self.length)
return NO;
if (self.isIntegerNumberOnly)
return YES;
if (self.isFloatNumber)
return YES;
return NO;
}
- (BOOL)isIntegerNumberOnly
{
return [self rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location == NSNotFound;
}
- (BOOL)isFloatNumber
{
static NSCharacterSet *cs = nil;
if (!cs)
{
NSMutableCharacterSet *tmp = [NSMutableCharacterSet characterSetWithCharactersInString:@",."];
NSString *groupingSeperators = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
NSString *decimalSeperators = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
[tmp addCharactersInString:groupingSeperators];
[tmp addCharactersInString:decimalSeperators];
cs = tmp.immutableObject;
#if !__has_feature(objc_arc)
[cs retain];
#endif
}
return ([self rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) && ([self rangeOfCharacterFromSet:cs].location != NSNotFound);
}
- (BOOL)isWriteablePath
{
if (self.fileExists)
return NO;
if (![@"TEST" writeToFile:self atomically:YES encoding:NSUTF8StringEncoding error:NULL])
return NO;
[fileManager removeItemAtPath:self error:NULL];
return YES;
}
- (BOOL)isValidEmail
{
if (self.length > 254)
return NO;
NSArray <NSString *> *portions = [self split:@"@"];
if (portions.count != 2)
return FALSE;
NSString *local = portions[0];
NSString *domain = portions[1];
if (![domain contains:@"."])
return FALSE;
static NSCharacterSet *localValid = nil, *domainValid = nil;
if (!localValid)
{
localValid = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~."];
domainValid = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-."];
#if !__has_feature(objc_arc)
[localValid retain];
[domainValid retain];
#endif
}
if ([local rangeOfCharacterFromSet:localValid.invertedSet options:(NSStringCompareOptions)0].location != NSNotFound)
return NO;
if ([domain rangeOfCharacterFromSet:domainValid.invertedSet options:(NSStringCompareOptions)0].location != NSNotFound)
return NO;
return YES;
}
- (NSArray <NSString *> *)dirContents
{
return [fileManager contentsOfDirectoryAtPath:self error:NULL];
}
- (NSArray <NSString *> *)dirContentsRecursive
{
return [fileManager subpathsOfDirectoryAtPath:self error:NULL];
}
- (NSArray <NSString *> *)dirContentsAbsolute
{
NSArray <NSString *> *c = self.dirContents;
return [c mapped:^NSString *(NSString *input) { return [self stringByAppendingPathComponent:input]; }];
}
- (NSArray <NSString *> *)dirContentsRecursiveAbsolute
{
NSArray <NSString *> *c = self.dirContentsRecursive;
return [c mapped:^NSString *(NSString *input) { return [self stringByAppendingPathComponent:input]; }];
}
- (NSString *)uniqueFile
{
assert(fileManager);
if (![fileManager fileExistsAtPath:self])
return self;
else
{
NSString *ext = self.pathExtension;
NSString *namewithoutext = self.stringByDeletingPathExtension;
int i = 0;
while ([fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@-%i.%@", namewithoutext, i,ext]])
i++;
return [NSString stringWithFormat:@"%@-%i.%@", namewithoutext, i,ext];
}
}
- (void)setContents:(NSData *)data
{
NSError *err;
if (![data writeToFile:self options:NSDataWritingAtomic error:&err])
LOG(err);
}
- (NSData *)contents
{
#if __has_feature(objc_arc)
return [[NSData alloc] initWithContentsOfFile:self];
#else
return [[[NSData alloc] initWithContentsOfFile:self] autorelease];
#endif
}
- (BOOL)fileExists
{
assert(fileManager);
return [fileManager fileExistsAtPath:self];
}
- (NSUInteger)countOccurencesOfString:(NSString *)str
{
return [[self componentsSeparatedByString:str] count] - 1;
}
- (BOOL)contains:(NSString *)otherString
{
return ([self rangeOfString:otherString].location != NSNotFound);
}
- (BOOL)contains:(NSString *)otherString insensitive:(BOOL)insensitive
{
return ([self rangeOfString:otherString options:insensitive ? NSCaseInsensitiveSearch : 0].location != NSNotFound);
}
- (BOOL)containsAny:(NSArray *)otherStrings
{
for (NSString *otherString in otherStrings)
if ([self rangeOfString:otherString].location != NSNotFound)
return YES;
return NO;
}
- (NSString *)localized
{
return NSLocalizedString(self, nil);
}
- (NSString *)resourcePath
{
return [bundle pathForResource:self ofType:nil];
}
- (NSURL *)resourceURL
{
return [bundle URLForResource:self withExtension:nil];
}
- (NSURL *)URL
{
return [NSURL URLWithString:self];
}
- (NSURL *)fileURL
{
return [NSURL fileURLWithPath:self];
}
- (NSString *)expanded
{
return [self stringByExpandingTildeInPath];
}
- (NSArray <NSString *> *)words
{
return [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
- (NSArray <NSString *> *)lines
{
return [self componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
- (NSAttributedString *)hyperlinkWithURL:(NSURL *)url
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
[attributedString beginEditing];
[attributedString addAttribute:NSLinkAttributeName value:url.absoluteString range:self.fullRange];
[attributedString addAttribute:NSForegroundColorAttributeName value:makeColor(0, 0, 1, 1) range:self.fullRange];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:self.fullRange];
[attributedString endEditing];
#if ! __has_feature(objc_arc)
[attributedString autorelease];
#endif
return attributedString;
}
- (NSString *)trimmedOfWhitespace
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
- (NSString *)trimmedOfWhitespaceAndNewlines
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString *)clamp:(NSUInteger)maximumLength
{
return (([self length] <= maximumLength) ? self : [self substringToIndex:maximumLength]);
}
- (NSString *)stringByReplacingMultipleStrings:(NSDictionary *)replacements
{
NSString *ret = self;
assert(![self contains:@"k9BBV15zFYi44YyB"]);
for (NSString *key in replacements)
{
if ([[NSNull null] isEqual:key] || [[NSNull null] isEqual:replacements[key]])
continue;
ret = [ret stringByReplacingOccurrencesOfString:key
withString:[key stringByAppendingString:@"k9BBV15zFYi44YyB"]];
}
BOOL replaced;
do
{
replaced = FALSE;
for (NSString *key in replacements)
{
id value = replacements[key];
if ([[NSNull null] isEqual:key] || [[NSNull null] isEqual:value])
continue;
NSString *tmp = [ret stringByReplacingOccurrencesOfString:[key stringByAppendingString:@"k9BBV15zFYi44YyB"]
withString:value];
if (![tmp isEqualToString:ret])
{
ret = tmp;
replaced = YES;
}
}
} while (replaced);
return ret;
}
- (NSString *)capitalizedStringWithUppercaseWords:(NSArray <NSString *> *)uppercaseWords
{
NSString *res = self.capitalizedString;
for (NSString *word in uppercaseWords)
{
res = [res stringByReplacingOccurrencesOfString:makeString(@"(\\W)%@(\\W)", word.capitalizedString)
withString:makeString(@"$1%@$2", word.uppercaseString)
options:NSRegularExpressionSearch range: res.fullRange];
}
for (NSString *word in uppercaseWords)
{
res = [res stringByReplacingOccurrencesOfString:makeString(@"(\\W)%@(\\Z)", word.capitalizedString)
withString:makeString(@"$1%@", word.uppercaseString)
options:NSRegularExpressionSearch range:res.fullRange];
}