1# LZ4 API Example : Dictionary Random Access
2
3`dictionaryRandomAccess.c` is LZ4 API example which implements dictionary compression and random access decompression.
4
5Please note that the output file is not compatible with lz4frame and is platform dependent.
6
7
8## What's the point of this example ?
9
10 - Dictionary based compression for homogenous files.
11 - Random access to compressed blocks.
12
13
14## How the compression works
15
16Reads the dictionary from a file, and uses it as the history for each block.
17This allows each block to be independent, but maintains compression ratio.
18
19```
20    Dictionary
21         +
22         |
23         v
24    +---------+
25    | Block#1 |
26    +----+----+
27         |
28         v
29      {Out#1}
30
31
32    Dictionary
33         +
34         |
35         v
36    +---------+
37    | Block#2 |
38    +----+----+
39         |
40         v
41      {Out#2}
42```
43
44After writing the magic bytes `TEST` and then the compressed blocks, write out the jump table.
45The last 4 bytes is an integer containing the number of blocks in the stream.
46If there are `N` blocks, then just before the last 4 bytes is `N + 1` 4 byte integers containing the offsets at the beginning and end of each block.
47Let `Offset#K` be the total number of bytes written after writing out `Block#K` *including* the magic bytes for simplicity.
48
49```
50+------+---------+     +---------+---+----------+     +----------+-----+
51| TEST | Block#1 | ... | Block#N | 4 | Offset#1 | ... | Offset#N | N+1 |
52+------+---------+     +---------+---+----------+     +----------+-----+
53```
54
55## How the decompression works
56
57Decompression will do reverse order.
58
59 - Seek to the last 4 bytes of the file and read the number of offsets.
60 - Read each offset into an array.
61 - Seek to the first block containing data we want to read.
62   We know where to look because we know each block contains a fixed amount of uncompressed data, except possibly the last.
63 - Decompress it and write what data we need from it to the file.
64 - Read the next block.
65 - Decompress it and write that page to the file.
66
67Continue these procedure until all the required data has been read.
68