···301301```
302302303303The `key` and `value` are binaries, and the `version` is the integer database version.
304304+305305+306306+## Merge
307307+308308+A k-way merge takes multiple sorted input streams (tables and memtables) and produces a single sorted output stream.
309309+This operation is used for both reads *and* writes.
310310+311311+To perform a merge, a priority queue of iterators is used, with one iterator for each memtable and each level of tables.
312312+The priority queue is keyed by database keys, so the next iterator in the queue contains the next key.
313313+This queue is implemented as a tree using `:gb_trees`,
314314+but a more efficient data structure may be future work (loser trees are known to be optimal).
315315+316316+### Memtable Iterator
317317+318318+The memtable iterator stores a reference to the memtable (an `:ets` table) and the current key.
319319+Iteration is performed by calling `:ets.next()`.
320320+321321+### Level Iterator
322322+323323+The level iterator is used to iterate over the keys of an entire level.
324324+After each subtable is exhausted, the iterator moves to the next subtable using the index from the table.
325325+After each table is exhausted, the iterator moves to the next table by looking it up in the manifest.
326326+327327+Note that all manifest operations must take place at a particular manifest epoch for consistency.
328328+This is handled by the reader process.
329329+330330+The level iterator consists of the following:
331331+332332+```
333333+# Level Iterator
334334+{level, table, subtable, key_pos}
335335+```
336336+337337+The `level` is the (integer) level of the LSM being iterated.
338338+339339+The `table` and `subtable` hold decoded metadata and references needed to decode the the table/subtable being iterated.
340340+341341+The `key_pos` is the position of the key within the subtable.