-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSData.m
More file actions
4674 lines (4212 loc) · 109 KB
/
NSData.m
File metadata and controls
4674 lines (4212 loc) · 109 KB
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
/**
Copyright (C) 1995-2015 Free Software Foundation, Inc.
Written by: Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
Date: March 1995
Rewritten by: Richard Frith-Macdonald <richard@brainstorm.co.uk>
Date: September 1997
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSData class reference</title>
$Date$ $Revision$
*/
/* NOTES - Richard Frith-Macdonald 1997
*
* Rewritten to use the class cluster architecture as in OPENSTEP.
*
* NB. In our implementaion we require an extra primitive for the
* NSMutableData subclasses. This new primitive method is the
* [-setCapacity:] method, and it differs from [-setLength:]
* as follows -
*
* [-setLength:]
* clears bytes when the allocated buffer grows
* never shrinks the allocated buffer capacity
* [-setCapacity:]
* doesn't clear newly allocated bytes
* sets the size of the allocated buffer.
*
* The actual class hierarchy is as follows -
*
* NSData Abstract base class.
* NSDataStatic Concrete class static buffers.
* NSDataEmpty Concrete class static buffers.
* NSDataMalloc Concrete class.
* NSDataMappedFile Memory mapped files.
* NSDataShared Extension for shared memory.
* NSDataFinalized For GC of non-GC data.
* NSDataWithDeallocatorBlock Adds custom deallocation behaviour
* NSMutableData Abstract base class.
* NSMutableDataMalloc Concrete class.
* NSMutableDataShared Extension for shared memory.
* NSDataMutableFinalized For GC of non-GC data.
* NSMutableDataWithDeallocatorBlock Adds custom deallocation behaviour
*
* NSMutableDataMalloc MUST share it's initial instance variable layout
* with NSDataMalloc so that it can use the 'behavior' code to inherit
* methods from NSDataMalloc.
*
* Since all the other subclasses are based on NSDataMalloc or
* NSMutableDataMalloc, we can put most methods in here and not
* bother with duplicating them in the other classes.
*
*/
#import "common.h"
#if !defined (__GNU_LIBOBJC__)
# include <objc/encoding.h>
#endif
#import "GNUstepBase/GSObjCRuntime.h"
#import "Foundation/NSByteOrder.h"
#import "Foundation/NSCoder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSException.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSRange.h"
#import "Foundation/NSURL.h"
#import "Foundation/NSValue.h"
#import "GSPrivate.h"
#include <stdio.h>
#ifdef HAVE_MMAP
#include <sys/mman.h>
#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#elif defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#ifndef MAP_FAILED
#define MAP_FAILED ((void*)-1) /* Failure address. */
#endif
@class NSDataMappedFile;
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SHMCTL
#include <sys/ipc.h>
#include <sys/shm.h>
#define VM_RDONLY 0644 /* self read/write - other readonly */
#define VM_ACCESS 0666 /* read/write access for all */
@class NSDataShared;
@class NSMutableDataShared;
#endif
@class NSDataMalloc;
@class NSDataStatic;
@class NSMutableDataMalloc;
/*
* Some static variables to cache classes and methods for quick access -
* these are set up at process startup or in [NSData +initialize]
*/
static Class dataStatic;
static Class dataMalloc;
static Class mutableDataMalloc;
static Class dataBlock;
static Class mutableDataBlock;
static Class NSDataAbstract;
static Class NSMutableDataAbstract;
static SEL appendSel;
static IMP appendImp;
static inline void
decodebase64(unsigned char *dst, const unsigned char *src)
{
dst[0] = (src[0] << 2) | ((src[1] & 0x30) >> 4);
dst[1] = ((src[1] & 0x0F) << 4) | ((src[2] & 0x3C) >> 2);
dst[2] = ((src[2] & 0x03) << 6) | (src[3] & 0x3F);
}
static char b64[]
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const int crlf64 = NSDataBase64EncodingEndLineWithCarriageReturn
| NSDataBase64EncodingEndLineWithLineFeed;
static NSUInteger
encodebase64(unsigned char **dstRef,
const unsigned char *src,
NSUInteger length,
NSDataBase64EncodingOptions options)
{
unsigned char *dst;
NSUInteger dIndex = 0;
NSUInteger dIndexNoNewLines = 0;
NSUInteger sIndex;
NSUInteger lineLength;
NSUInteger destLen;
lineLength = 0;
if (options & NSDataBase64Encoding64CharacterLineLength)
lineLength = 64;
else if (options & NSDataBase64Encoding76CharacterLineLength)
lineLength = 76;
/* if no EndLine options are set but a line length is given,
* CR+LF is implied
*/
if (lineLength && !(options & crlf64))
{
options |= crlf64;
}
/* estimate destination length */
destLen = 4 * ((length + 2) / 3);
/* we need to take in account line-endings */
if (lineLength)
{
if ((options & crlf64) == crlf64)
destLen += (destLen / lineLength)*2; // CR and LF
else
destLen += (destLen / lineLength); // CR or LF
}
dst = NSZoneMalloc(NSDefaultMallocZone(), destLen);
for (sIndex = 0; sIndex < length; sIndex += 3)
{
int c0 = src[sIndex];
int c1 = (sIndex+1 < length) ? src[sIndex+1] : 0;
int c2 = (sIndex+2 < length) ? src[sIndex+2] : 0;
dst[dIndex++] = b64[(c0 >> 2) & 077];
dst[dIndex++] = b64[((c0 << 4) & 060) | ((c1 >> 4) & 017)];
dst[dIndex++] = b64[((c1 << 2) & 074) | ((c2 >> 6) & 03)];
dst[dIndex++] = b64[c2 & 077];
dIndexNoNewLines += 4;
if (lineLength && !(dIndexNoNewLines % lineLength) )
{
if (options & NSDataBase64EncodingEndLineWithCarriageReturn)
dst[dIndex++] = '\r';
if (options & NSDataBase64EncodingEndLineWithLineFeed)
dst[dIndex++] = '\n';
}
}
/* If len was not a multiple of 3, then we have encoded too
* many characters. Adjust appropriately.
*/
if (sIndex == length + 1)
{
/* There were only 2 bytes in that last group */
dst[dIndex - 1] = '=';
}
else if (sIndex == length + 2)
{
/* There was only 1 byte in that last group */
dst[dIndex - 1] = '=';
dst[dIndex - 2] = '=';
}
*dstRef = dst;
return dIndex;
}
static BOOL
readContentsOfFile(NSString *path, void **buf, off_t *len, NSZone *zone)
{
NSFileManager *mgr = [NSFileManager defaultManager];
NSDictionary *att;
#if defined(_WIN32)
const unichar *thePath = 0;
#else
const char *thePath = 0;
#endif
FILE *theFile = 0;
void *tmp = 0;
int c;
off_t fileLength;
#ifdef __ANDROID__
// Android: try using asset manager if path is in main bundle resources
AAsset *asset = [NSBundle assetForPath: path withMode: AASSET_MODE_BUFFER];
if (asset)
{
fileLength = AAsset_getLength(asset);
tmp = NSZoneMalloc(zone, fileLength);
if (tmp == 0)
{
NSLog(@"Malloc failed for file (%@) of length %jd - %@", path,
(intmax_t)fileLength, [NSError _last]);
AAsset_close(asset);
goto failure;
}
int result = AAsset_read(asset, tmp, fileLength);
AAsset_close(asset);
if (result < 0)
{
NSWarnFLog(@"read of file (%@) contents failed - %@", path,
[NSError errorWithDomain: NSPOSIXErrorDomain
code: result
userInfo: nil]);
goto failure;
}
*buf = tmp;
*len = fileLength;
return YES;
}
#endif /* __ANDROID__ */
#if defined(_WIN32)
thePath = (const unichar*)[path fileSystemRepresentation];
#else
thePath = [path fileSystemRepresentation];
#endif
if (thePath == 0)
{
NSWarnFLog(@"Open (%@) attempt failed - bad path", path);
return NO;
}
att = [mgr fileAttributesAtPath: path traverseLink: YES];
if (nil == att)
{
return NO; // No such file ... fail quietly
}
if ([att fileType] != NSFileTypeRegular)
{
NSWarnFLog(@"Open (%@) attempt failed - not a regular file", path);
return NO;
}
#if defined(_WIN32)
theFile = _wfopen(thePath, L"rb");
#else
theFile = fopen(thePath, "rb");
#endif
if (theFile == 0) /* We failed to open the file. */
{
NSDebugFLog(@"Open (%@) attempt failed - %@", path, [NSError _last]);
goto failure;
}
/*
* Seek to the end of the file.
*/
c = fseeko(theFile, 0, SEEK_END);
if (c != 0)
{
NSWarnFLog(@"Seek to end of file (%@) failed - %@", path,
[NSError _last]);
goto failure;
}
/*
* Determine the length of the file (having seeked to the end of the
* file) by calling ftello().
*/
fileLength = ftello(theFile);
if (fileLength == (off_t)-1)
{
NSWarnFLog(@"Ftell on %@ failed - %@", path, [NSError _last]);
goto failure;
}
if (fileLength >= 2147483647)
{
fileLength = 0;
}
/*
* Rewind the file pointer to the beginning, preparing to read in
* the file.
*/
c = fseeko(theFile, 0, SEEK_SET);
if (c != 0)
{
NSWarnFLog(@"Fseek to start of file (%@) failed - %@", path,
[NSError _last]);
goto failure;
}
clearerr(theFile);
if (fileLength == 0)
{
unsigned char buf[BUFSIZ];
/*
* Special case ... a file of length zero may be a named pipe or some
* file in the /proc filesystem, which will return us data if we read
* from it ... so we try reading as much as we can.
*/
while ((c = fread(buf, 1, BUFSIZ, theFile)) != 0)
{
if (tmp == 0)
{
tmp = NSZoneMalloc(zone, c);
}
else
{
tmp = NSZoneRealloc(zone, tmp, fileLength + c);
}
if (tmp == 0)
{
NSLog(@"Malloc failed for file (%@) of length %jd - %@", path,
(intmax_t)fileLength + c, [NSError _last]);
goto failure;
}
memcpy(tmp + fileLength, buf, c);
fileLength += c;
}
}
else
{
off_t offset = 0;
tmp = NSZoneMalloc(zone, fileLength);
if (tmp == 0)
{
NSLog(@"Malloc failed for file (%@) of length %jd - %@", path,
(intmax_t)fileLength, [NSError _last]);
goto failure;
}
while (offset < fileLength
&& (c = fread(tmp + offset, 1, fileLength - offset, theFile)) != 0)
{
offset += c;
}
if (offset < fileLength)
{
fileLength = offset;
tmp = NSZoneRealloc(zone, tmp, fileLength);
}
}
if (ferror(theFile))
{
NSWarnFLog(@"read of file (%@) contents failed - %@", path,
[NSError _last]);
goto failure;
}
*buf = tmp;
*len = fileLength;
fclose(theFile);
return YES;
/*
* Just in case the failure action needs to be changed.
*/
failure:
{
NSZoneFree(zone, tmp);
}
if (theFile != 0)
{
fclose(theFile);
}
return NO;
}
/*
* NB, The start of the NSMutableDataMalloc instance variables must be
* identical to that of NSDataMalloc in order to inherit its methods.
*/
@interface NSDataStatic : NSData
{
NSUInteger length;
__strong void *bytes;
/**
* This is a GSDataDeallocatorBlock instance, stored as an id for backwards
* compatibility.
*/
id deallocator;
}
@end
@interface NSDataEmpty: NSDataStatic
@end
@interface NSDataMalloc : NSDataStatic
@end
@interface NSDataWithDeallocatorBlock : NSDataMalloc
@end
@interface NSMutableDataMalloc : NSMutableData
{
NSUInteger length;
__strong void *bytes;
/**
* This is a GSDataDeallocatorBlock instance, stored as an id for backwards
* compatibility.
*/
id deallocator;
NSZone *zone;
NSUInteger capacity;
NSUInteger growth;
}
/* Increase capacity to at least the specified minimum value. */
- (void) _grow: (NSUInteger)minimum;
@end
@interface NSMutableDataWithDeallocatorBlock : NSMutableDataMalloc
@end
#ifdef HAVE_MMAP
@interface NSDataMappedFile : NSDataMalloc
@end
#endif
#ifdef HAVE_SHMCTL
@interface NSDataShared : NSDataMalloc
{
int shmid;
}
- (id) initWithShmID: (int)anId length: (NSUInteger)bufferSize;
@end
@interface NSMutableDataShared : NSMutableDataMalloc
{
int shmid;
}
- (id) initWithShmID: (int)anId length: (NSUInteger)bufferSize;
@end
#endif
/**
* <p>Class for storing a byte array. Methods for initializing from memory a
* file, or the network are provided, as well as the ability to write to a
* file or the network. If desired, object can take over management of a
* pre-allocated buffer (with malloc or similar), free'ing it when deallocated.
* </p>
* <p>The data buffer at any given time has a <em>capacity</em>, which is the
* size of its allocated memory area, in bytes, and a <em>length</em>, which
* is the length of data it is currently storing.</p>
*/
@implementation NSData
- (NSUInteger) sizeOfContentExcluding: (NSHashTable*)exclude
{
return [self length];
}
+ (void) initialize
{
if (self == [NSData class])
{
NSDataAbstract = self;
NSMutableDataAbstract = [NSMutableData class];
dataStatic = [NSDataStatic class];
dataMalloc = [NSDataMalloc class];
dataBlock = [NSDataWithDeallocatorBlock class];
mutableDataMalloc = [NSMutableDataMalloc class];
mutableDataBlock = [NSMutableDataWithDeallocatorBlock class];
appendSel = @selector(appendBytes:length:);
appendImp = [mutableDataMalloc instanceMethodForSelector: appendSel];
}
}
+ (id) allocWithZone: (NSZone*)z
{
if (self == NSDataAbstract)
{
return NSAllocateObject(dataMalloc, 0, z);
}
else
{
return NSAllocateObject(self, 0, z);
}
}
/**
* Returns an empty data object.
*/
+ (id) data
{
static NSData *empty = nil;
if (empty == nil)
{
empty = [dataStatic allocWithZone: NSDefaultMallocZone()];
empty = [empty initWithBytesNoCopy: 0 length: 0 freeWhenDone: NO];
}
return empty;
}
/**
* Returns an autoreleased data object containing data copied from bytes
* and with the specified length. Invokes -initWithBytes:length:
*/
+ (id) dataWithBytes: (const void*)bytes
length: (NSUInteger)length
{
NSData *d;
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithBytes: bytes length: length];
return AUTORELEASE(d);
}
/**
* Returns an autoreleased data object encapsulating the data at bytes
* and with the specified length. Invokes
* -initWithBytesNoCopy:length:freeWhenDone: with YES
*/
+ (id) dataWithBytesNoCopy: (void*)bytes
length: (NSUInteger)length
{
NSData *d;
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithBytesNoCopy: bytes length: length freeWhenDone: YES];
return AUTORELEASE(d);
}
/**
* Returns an autoreleased data object encapsulating the data at bytes
* and with the specified length. Invokes
* -initWithBytesNoCopy:length:freeWhenDone:
*/
+ (id) dataWithBytesNoCopy: (void*)aBuffer
length: (NSUInteger)bufferSize
freeWhenDone: (BOOL)shouldFree
{
NSData *d;
if (shouldFree == YES)
{
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
}
else
{
d = [dataStatic allocWithZone: NSDefaultMallocZone()];
}
d = [d initWithBytesNoCopy: aBuffer
length: bufferSize
freeWhenDone: shouldFree];
return AUTORELEASE(d);
}
/**
* Returns a data object encapsulating the contents of the specified file.
* Invokes -initWithContentsOfFile:
*/
+ (id) dataWithContentsOfFile: (NSString*)path
{
NSData *d;
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithContentsOfFile: path];
return AUTORELEASE(d);
}
/**
* Returns a data object encapsulating the contents of the specified
* file mapped directly into memory.
* Invokes -initWithContentsOfMappedFile:
*/
+ (id) dataWithContentsOfMappedFile: (NSString*)path
{
NSData *d;
#ifdef HAVE_MMAP
d = [NSDataMappedFile allocWithZone: NSDefaultMallocZone()];
d = [d initWithContentsOfMappedFile: path];
#else
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithContentsOfMappedFile: path];
#endif
return AUTORELEASE(d);
}
/**
* Retrieves the information at the specified url and returns an NSData
* instance encapsulating it.
*/
+ (id) dataWithContentsOfURL: (NSURL*)url
{
NSData *d;
d = [url resourceDataUsingCache: YES];
return d;
}
/**
* Returns an autoreleased instance initialised by copying the contents of data.
*/
+ (id) dataWithData: (NSData*)data
{
NSData *d;
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithBytes: [data bytes] length: [data length]];
return AUTORELEASE(d);
}
/**
* Returns a new empty data object.
*/
+ (id) new
{
NSData *d;
d = [dataMalloc allocWithZone: NSDefaultMallocZone()];
d = [d initWithBytesNoCopy: 0 length: 0 freeWhenDone: YES];
return d;
}
- (id) init
{
return [self initWithBytesNoCopy: 0 length: 0 freeWhenDone: YES];
}
- (id) initWithBase64EncodedData: (NSData*)base64Data
options: (NSDataBase64DecodingOptions)options
{
NSUInteger length;
NSUInteger declen;
const unsigned char *src;
const unsigned char *end;
unsigned char *result;
unsigned char *dst;
unsigned char buf[4];
unsigned pos = 0;
NSZone *zone = [self zone];
if (nil == base64Data)
{
AUTORELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"[%@-initWithBase64EncodedData:options:] called with "
@"nil data", NSStringFromClass([self class])];
return nil;
}
length = [base64Data length];
if (length == 0)
{
return [self initWithBytesNoCopy: 0 length: 0 freeWhenDone: YES];
}
declen = ((length + 3) * 3)/4;
src = (const unsigned char*)[base64Data bytes];
end = &src[length];
result = NSZoneMalloc(zone, declen);
dst = result;
while (src != end)
{
int c = *src++;
if (isupper(c))
{
c -= 'A';
}
else if (islower(c))
{
c = c - 'a' + 26;
}
else if (isdigit(c))
{
c = c - '0' + 52;
}
else if (c == '/')
{
c = 63;
}
else if (c == '+')
{
c = 62;
}
else if (c == '=')
{
/* Only legal as padding at end of string */
while (src != end)
{
c = *src++;
if (c != '=')
{
if (options & NSDataBase64DecodingIgnoreUnknownCharacters)
{
if (!isupper(c) && !islower(c) && !isdigit(c)
&& c != '/' && c != '+')
{
continue; // An unknown character
}
}
free(result);
DESTROY(self);
return nil;
}
}
/* For OSX compatibility, if we have unnecessary padding at the
* end of a string, we treat it as representing a zero byte.
*/
if (0 == pos)
{
*dst++ = '\0';
}
c = -1;
}
else if (options & NSDataBase64DecodingIgnoreUnknownCharacters)
{
c = -1; /* ignore */
}
else
{
free(result);
DESTROY(self);
return nil;
}
if (c >= 0)
{
buf[pos++] = c;
if (pos == 4)
{
pos = 0;
decodebase64(dst, buf);
dst += 3;
}
}
}
if (pos > 0)
{
unsigned i;
for (i = pos; i < 4; i++)
{
buf[i] = '\0';
}
pos--;
if (pos > 0)
{
unsigned char tail[3];
decodebase64(tail, buf);
memcpy(dst, tail, pos);
dst += pos;
}
}
length = dst - result;
if (options & NSDataBase64DecodingIgnoreUnknownCharacters)
{
/* If the decoded length is a lot shorter than expected (because we
* ignored a lot of characters), reallocate to get smaller memory.
*/
if ((((declen - length) * 100) / declen) > 5)
{
result = NSZoneRealloc(zone, result, length);
}
}
return [self initWithBytesNoCopy: result length: length freeWhenDone: YES];
}
- (id) initWithBase64EncodedString: (NSString*)base64String
options: (NSDataBase64DecodingOptions)options
{
NSData *data;
if (nil == base64String)
{
AUTORELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"[%@-initWithBase64EncodedString:options:] called with "
@"nil string", NSStringFromClass([self class])];
return nil;
}
data = [base64String dataUsingEncoding: NSUTF8StringEncoding];
return [self initWithBase64EncodedData: data options: options];
}
/**
* Makes a copy of bufferSize bytes of data at aBuffer, and passes it to
* -initWithBytesNoCopy:length:freeWhenDone: with a YES argument in order
* to initialise the receiver. Returns the result.
*/
- (id) initWithBytes: (const void*)aBuffer
length: (NSUInteger)bufferSize
{
void *ptr = 0;
if (bufferSize > 0)
{
if (aBuffer == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-initWithBytes:length:] called with "
@"length but null bytes", NSStringFromClass([self class])];
}
ptr = NSAllocateCollectable(bufferSize, 0);
if (ptr == 0)
{
DESTROY(self);
return nil;
}
memcpy(ptr, aBuffer, bufferSize);
}
return [self initWithBytesNoCopy: ptr
length: bufferSize
freeWhenDone: YES];
}
/**
* Invokes -initWithBytesNoCopy:length:freeWhenDone: with the last argument
* set to YES. Returns the resulting initialised data object (which may not
* be the receiver).
*/
- (id) initWithBytesNoCopy: (void*)aBuffer
length: (NSUInteger)bufferSize
{
return [self initWithBytesNoCopy: aBuffer
length: bufferSize
freeWhenDone: YES];
}
/** <init /><override-subclass />
* Initialises the receiver.<br />
* The value of aBuffer is a pointer to something to be stored.<br />
* The value of bufferSize is the number of bytes to use.<br />
* The value of shouldFree specifies whether the receiver should
* attempt to free the memory pointer to by aBuffer when the receiver
* is deallocated ... ie. it says whether the receiver <em>owns</em>
* the memory. Supplying the wrong value here will lead to memory
* leaks or crashes.
*/
- (id) initWithBytesNoCopy: (void*)aBuffer
length: (NSUInteger)bufferSize
freeWhenDone: (BOOL)shouldFree
{
[self subclassResponsibility: _cmd];
return nil;
}
- (instancetype) initWithBytesNoCopy: (void*)bytes
length: (NSUInteger)length
deallocator: (GSDataDeallocatorBlock)deallocator
{
[self subclassResponsibility: _cmd];
return nil;
}
/**
* Initialises the receiver with the contents of the specified file.<br />
* Returns the resulting object.<br />
* Returns nil if the file does not exist or can not be read for some reason.
*/
- (id) initWithContentsOfFile: (NSString*)path
{
void *fileBytes;
off_t fileLength;
if (readContentsOfFile(path, &fileBytes, &fileLength, [self zone]) == NO)
{
DESTROY(self);
return nil;
}
self = [self initWithBytesNoCopy: fileBytes
length: (NSUInteger)fileLength
freeWhenDone: YES];
return self;
}
/**
* Initialize with data pointing to contents of file at path. Bytes are
* only "swapped in" as needed. File should not be moved or deleted for
* the life of this object.
*/
- (id) initWithContentsOfMappedFile: (NSString *)path
{
#ifdef HAVE_MMAP
NSZone *z = [self zone];
DESTROY(self);
self = [NSDataMappedFile allocWithZone: z];
return [self initWithContentsOfMappedFile: path];
#else
return [self initWithContentsOfFile: path];
#endif
}
/**
* Initialize with data pointing to contents of URL, which will be
* retrieved immediately in a blocking manner.
*/
- (id) initWithContentsOfURL: (NSURL*)url
{
NSData *data = [url resourceDataUsingCache: YES];
return [self initWithData: data];
}
/**
* Initializes by copying data's bytes into a new buffer.
*/
- (id) initWithData: (NSData*)data
{
if (data == nil)
{
return [self initWithBytesNoCopy: 0 length: 0 freeWhenDone: YES];
}
if ([data isKindOfClass: [NSData class]] == NO)
{
NSLog(@"-initWithData: passed a non-data object");
DESTROY(self);
return nil;
}
return [self initWithBytes: [data bytes] length: [data length]];
}
// Accessing Data
/** <override-subclass>
* Returns a pointer to the data encapsulated by the receiver.
*/
- (const void*) bytes
{
[self subclassResponsibility: _cmd];
return 0;
}
/**
* Returns a short description of this object.
*/
- (NSString*) description
{
extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
NSMutableString *result = nil;