Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 51 lines (42 sloc) 1.168 kb
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
1 //
2 // NSData+reallyMapped.m
3 // MapTest
4 //
5 // Created by Tom Harrington on 1/31/12.
6 // Copyright (c) 2012 Atomic Bird, LLC. All rights reserved.
7 //
8
9 #import "NSData+reallyMapped.h"
10 #import <sys/fcntl.h>
11 #import <sys/mman.h>
2758992 @atomicbird Update file size code.
authored
12 #include <sys/stat.h>
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
13 #import "NSObject+deallocBlock.h"
14
15 @implementation NSData (reallyMapped)
16
17 + (NSData *)dataWithContentsOfReallyMappedFile:(NSString *)path;
18 {
19 // Get an fd
20 int fd = open([path fileSystemRepresentation], O_RDONLY);
21 if (fd < 0) {
22 return nil;
23 }
24
25 // Get file size
2758992 @atomicbird Update file size code.
authored
26 struct stat statbuf;
27 if (fstat(fd, &statbuf) == -1) {
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
28 close(fd);
29 return nil;
30 }
31
32 // mmap
33 void *mappedFile;
2758992 @atomicbird Update file size code.
authored
34 mappedFile = mmap(0, statbuf.st_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
a72dae4 @atomicbird Convert tabs to spaces
authored
35 close(fd);
36 if (mappedFile == MAP_FAILED) {
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
37 NSLog(@"Map failed, errno=%d, %s", errno, strerror(errno));
38 return nil;
a72dae4 @atomicbird Convert tabs to spaces
authored
39 }
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
40
a72dae4 @atomicbird Convert tabs to spaces
authored
41 // Create the NSData
2758992 @atomicbird Update file size code.
authored
42 NSData *mappedData = [NSData dataWithBytesNoCopy:mappedFile length:statbuf.st_size freeWhenDone:NO];
a72dae4 @atomicbird Convert tabs to spaces
authored
43
44 [mappedData addDeallocBlock:^{
2758992 @atomicbird Update file size code.
authored
45 munmap(mappedFile, statbuf.st_size);
a72dae4 @atomicbird Convert tabs to spaces
authored
46 }];
a0dbc1b @atomicbird Add NSObject+deallocBlock and NSData+reallyMapped
authored
47 return mappedData;
48 }
49
50 @end
Something went wrong with that request. Please try again.