What’s the recommended way to memory-map a file?

As the title says, I’m wondering what is the recommended way to memory-map a file (or part of a file) in Swift.

I see that Foundation includes the mmap function, but it is very un-Swifty with no argument labels and minimal documentation.

I also see that the Data.dataWithContentsOfMappedFile initializer has been deprecated for several years.

So, what’s the right approach here?

2 Likes

I'd try one of the Data methods: (contentsOf:url options: .alwaysMapped). It's not clear whether this returns an error if the file can't be mapped, but it sort of sounds like it does.

2 Likes

Foundation's APIs are probably what you want if you care about portability. Windows does not have mmap, but it does have MapViewOfFile that allows you to work with memory mappings of files.

1 Like

Also, note that mmap is not a Foundation function, it is being reexported from an underlying C module (Darwin on macOS or Glibc on Linux).

3 Likes

Data.ReadingOptions are documented as hints only, so there shouldn't be an error.

.alwaysMapped versus .mappedIfSafe is described in the Foundation Release Notes:

Safe File Mapping for NSData

Before iOS 5, specifying NSDataReadingMapped (or NSMappedRead) for -initWithContentsOfFile:options:error: would cause NSData to always attempt to map in the specified file. However, in some situations, mapping a file can be dangerous. For example, when NSData maps a file from a USB device or over the network the existence of said file can't be guaranteed for the lifetime of the object. Accessing the NSData's bytes after the mapped file disappears will likely cause unpredictable crashes in your application.

For applications linked on iOS 5 or later, NSDataReadingMapped will now only map the requested file if it can determine that mapping the file will be relatively safe. To reflect this change, NSDataReadingMapped has been deprecated and is now an alias for NSDataReadingMappedIfSafe.

The methods -dataWithContentsOfMappedFile: and -initWithContentsOfMappedFile: have been deprecated. In the very rare event that your application needs to map a file regardless of safety, you may use the NSDataReadingMappedAlways option.

3 Likes

Thanks

1 Like