diff options
Diffstat (limited to 'src/huffman/huffmanencoder.nim')
-rw-r--r-- | src/huffman/huffmanencoder.nim | 10 |
1 files changed, 5 insertions, 5 deletions
diff --git a/src/huffman/huffmanencoder.nim b/src/huffman/huffmanencoder.nim index 5ae1a68..09c6701 100644 --- a/src/huffman/huffmanencoder.nim +++ b/src/huffman/huffmanencoder.nim | |||
@@ -19,22 +19,22 @@ import ../bitio/integers, ../bitio/bitwriter | |||
19 | import huffmantree | 19 | import huffmantree |
20 | 20 | ||
21 | type HuffmanEncoder*[T, U: SomeUnsignedInt] = object | 21 | type HuffmanEncoder*[T, U: SomeUnsignedInt] = object |
22 | codebook: TableRef[T, U] | 22 | codebook: TableRef[T, tuple[bitLength: int, value: U]] |
23 | 23 | ||
24 | proc buildCodebook*[T, U](tree: HuffmanTreeNode[T], codeType: typedesc[U]): TableRef[T, U] = | 24 | proc buildCodebook*[T, U](tree: HuffmanTreeNode[T], codeType: typedesc[U]): TableRef[T, tuple[bitLength: int, value: U]] = |
25 | var codebook = newTable[T, U]() | 25 | var codebook = newTable[T, tuple[bitLength: int, value: U]]() |
26 | proc addCode(node: HuffmanTreeNode[T], path: U, depth: int) = | 26 | proc addCode(node: HuffmanTreeNode[T], path: U, depth: int) = |
27 | case node.kind: | 27 | case node.kind: |
28 | of branch: | 28 | of branch: |
29 | addCode(node.left, path, depth + 1) | 29 | addCode(node.left, path, depth + 1) |
30 | addCode(node.right, path or (1.U shl depth), depth + 1) | 30 | addCode(node.right, path or (1.U shl depth), depth + 1) |
31 | of leaf: | 31 | of leaf: |
32 | codebook[node.value] = path | 32 | codebook[node.value] = (depth, path) |
33 | addCode(tree, 0.U, 0) | 33 | addCode(tree, 0.U, 0) |
34 | codebook | 34 | codebook |
35 | 35 | ||
36 | proc encoder*[T, U](tree: HuffmanTreeNode[T], codeType: typedesc[U]): HuffmanEncoder[T, U] = | 36 | proc encoder*[T, U](tree: HuffmanTreeNode[T], codeType: typedesc[U]): HuffmanEncoder[T, U] = |
37 | HuffmanEncoder[T, U](codebook: buildCodebook(tree, codeType)) | 37 | HuffmanEncoder[T, U](codebook: buildCodebook(tree, codeType)) |
38 | 38 | ||
39 | proc encode*[T, U](decoder: HuffmanEncoder[T, U], value: T): U = | 39 | proc encode*[T, U](decoder: HuffmanEncoder[T, U], value: T): tuple[bitLength: int, value: U] = |
40 | decoder.codebook[value] | 40 | decoder.codebook[value] |