Permalink
Browse files

Update file size code.

Since we have an Unix file descriptor anyway, use Unix fstat() to get the file size instead of bringing NSFileManager and an NSNumber into it. From a suggestion by bazineta.
  • Loading branch information...
1 parent cc87aa6 commit 27589925f610195f4669690bd199eb64ff5c2db6 @atomicbird committed Feb 21, 2012
Showing with 6 additions and 6 deletions.
  1. +6 −6 NSData+reallyMapped.m
View
@@ -9,6 +9,7 @@
#import "NSData+reallyMapped.h"
#import <sys/fcntl.h>
#import <sys/mman.h>
+#include <sys/stat.h>
#import "NSObject+deallocBlock.h"
@implementation NSData (reallyMapped)
@@ -22,27 +23,26 @@ + (NSData *)dataWithContentsOfReallyMappedFile:(NSString *)path;
}
// Get file size
- NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
- if (fileAttributes == nil) {
+ struct stat statbuf;
+ if (fstat(fd, &statbuf) == -1) {
close(fd);
return nil;
}
- NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
// mmap
void *mappedFile;
- mappedFile = mmap(0, [fileSize intValue], PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
+ mappedFile = mmap(0, statbuf.st_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
close(fd);
if (mappedFile == MAP_FAILED) {
NSLog(@"Map failed, errno=%d, %s", errno, strerror(errno));
return nil;
}
// Create the NSData
- NSData *mappedData = [NSData dataWithBytesNoCopy:mappedFile length:[fileSize intValue] freeWhenDone:NO];
+ NSData *mappedData = [NSData dataWithBytesNoCopy:mappedFile length:statbuf.st_size freeWhenDone:NO];
[mappedData addDeallocBlock:^{
- munmap(mappedFile, [fileSize intValue]);
+ munmap(mappedFile, statbuf.st_size);
}];
return mappedData;
}

0 comments on commit 2758992

Please sign in to comment.