aboutsummaryrefslogtreecommitdiff
path: root/src/huffman/huffmantreebuilder.nim
diff options
context:
space:
mode:
Diffstat (limited to 'src/huffman/huffmantreebuilder.nim')
-rw-r--r--src/huffman/huffmantreebuilder.nim44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/huffman/huffmantreebuilder.nim b/src/huffman/huffmantreebuilder.nim
new file mode 100644
index 0000000..4169099
--- /dev/null
+++ b/src/huffman/huffmantreebuilder.nim
@@ -0,0 +1,44 @@
1# gzip-like LZSS compressor
2# Copyright (C) 2018 Pacien TRAN-GIRARD
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as
6# published by the Free Software Foundation, either version 3 of the
7# License, or (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17import tables, heapqueue
18import huffmantree
19
20type WeighedHuffmanTreeNode[T] = ref object
21 weight: int
22 huffmanTreeNode: HuffmanTreeNode[T]
23
24proc weighedHuffmanBranch[T](left, right: WeighedHuffmanTreeNode[T]): WeighedHuffmanTreeNode[T] =
25 WeighedHuffmanTreeNode[T](
26 weight: left.weight + right.weight,
27 huffmanTreeNode: huffmanBranch(left.huffmanTreeNode, right.huffmanTreeNode))
28
29proc weighedHuffmanLeaf[T](value: T, weight: int): WeighedHuffmanTreeNode[T] =
30 WeighedHuffmanTreeNode[T](
31 weight: weight,
32 huffmanTreeNode: huffmanLeaf(value))
33
34proc `<`*[T](left, right: WeighedHuffmanTreeNode[T]): bool =
35 left.weight < right.weight
36
37proc symbolQueue[T](stats: CountTableRef[T]): HeapQueue[WeighedHuffmanTreeNode[T]] =
38 result = newHeapQueue[WeighedHuffmanTreeNode[T]]()
39 for item, count in stats.pairs: result.push(weighedHuffmanLeaf(item, count))
40
41proc buildHuffmanTree*[T: SomeUnsignedInt](stats: CountTableRef[T]): HuffmanTreeNode[T] =
42 var symbolQueue = symbolQueue(stats)
43 while symbolQueue.len > 1: symbolQueue.push(weighedHuffmanBranch(symbolQueue.pop(), symbolQueue.pop()))
44 symbolQueue[0].huffmanTreeNode