From a34ae9e095033da30e501194cfa98801dcca3a48 Mon Sep 17 00:00:00 2001 From: AbsoluteZero000 Date: Sat, 5 Oct 2024 20:53:38 +0300 Subject: [PATCH] feat: added seralization --- huffman/huffman.go | 35 +++++++++++++++++++++++++++++++++++ huffman/huffman_util.go | 34 ++++++++++++++++++++++++++++++++++ huffman/util.go | 38 -------------------------------------- main.go | 9 ++++++++- 4 files changed, 77 insertions(+), 39 deletions(-) delete mode 100644 huffman/util.go diff --git a/huffman/huffman.go b/huffman/huffman.go index 5a3ca7c..bf98bce 100644 --- a/huffman/huffman.go +++ b/huffman/huffman.go @@ -1,6 +1,8 @@ package huffman import ( + "bytes" + "encoding/gob" "fmt" ) @@ -50,3 +52,36 @@ func Decode(root *Node, encodedData []byte, bitLength int, verbose bool) string } return decodedData } + +func SerializeTree(root *Node) ([]byte, error) { + if root == nil { + return nil, nil + } + + var buf bytes.Buffer + enc := gob.NewEncoder(&buf) + + err := enc.Encode(root) + if err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +func DeserializeTree(data []byte) (*Node, error) { + if data == nil { + return nil, nil + } + + buf := bytes.NewBuffer(data) + dec := gob.NewDecoder(buf) + + var root Node + err := dec.Decode(&root) + if err != nil { + return nil, err + } + + return &root, nil +} diff --git a/huffman/huffman_util.go b/huffman/huffman_util.go index 1b6619e..696e649 100644 --- a/huffman/huffman_util.go +++ b/huffman/huffman_util.go @@ -1,7 +1,9 @@ package huffman import ( + "bytes" "container/heap" + "math" ) type Node struct { @@ -114,3 +116,35 @@ func encodeString(s string, codes map[rune]string) string { } return encoded } + +func bitStringToBytes(s string) []byte { + numBytes := int(math.Ceil(float64(len(s)) / 8.0)) + result := make([]byte, numBytes) + + for i := 0; i < len(s); i++ { + if s[i] == '1' { + byteIndex := i / 8 + bitIndex := 7 - (i % 8) + result[byteIndex] |= 1 << bitIndex + } + } + + return result +} + +func bytesToBitString(data []byte, bitLength int) string { + var result bytes.Buffer + + for i := 0; i < bitLength; i++ { + byteIndex := i / 8 + bitIndex := 7 - (i % 8) + + if data[byteIndex]&(1<