Compress a string, write it to the file system, and decompress the same file using buffer compression.
In this article, you'll learn how to compress and decompress a
Create the Source Data
Typically, your app would dynamically generate the source data that it compresses, but for this example, the source data is a hard-coded string:
source is an array of
UInt8 values containing the UTF-8 representation of the source string.
Create the Destination Buffer
Unsafe structure and allocate it with a capacity of the source string's count to receive the encoded data:
Select a Compression Algorithm
If speed and compression ratio are important, use
Compress the Data
compression function compresses the data, writing the result to the destination buffer and returning the size of the encoded data:
When working with small files, the compression may fail and
You may elect to handle this situation differently, for example, by displaying a warning to the user that the compression failed.
Write the Encoded Data to a File
The following code writes the encoded data to a file in the the app's temporary directory on macOS:
Read the Encoded Data from a File
To read the encoded file, create a file handle for reading for the encoded file's URL:
Use the file handle to read the entire encoded data and populate
Decompress the Data
Allocate memory to contain the decoded data. Typically, the encoded payload would be part of a larger structure containing additional metadata such as the uncompressed size, and you'd use that to define the buffer capacity. However, for this example, allocate 8 MB:
compression to decode the raw bytes of the encoded source data, writing the result to
decoded. You can create a string from the destination buffer using the
compression function returns the size of the decoded data. If the decompression fails, the size returned is zero. This may indicate that the memory allocated to the destination buffer is insufficient and you should switch to the stream API or retry with a larger buffer.