-
Notifications
You must be signed in to change notification settings - Fork 1
/
mtf.hpp
105 lines (95 loc) · 2.58 KB
/
mtf.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//
// mtf.hpp
// pzip
//
// Created by Phuc Nguyen on 07/21/20.
// Copyright © 2020 Phuc Nguyen. All rights reserved.
//
#include "linked_list.hpp"
#include <deque>
#include <iostream>
using namespace std;
vector<uint8_t> MTF_encode(const vector<uint8_t>& input) {
list dict;
//Establish the list
for (size_t i = 0; i < 256; i++) {
dict.insert_back((uint8_t)i);
}
vector<uint8_t> res(input.size());
for (size_t i = 0; i < input.size(); i++) {
int dist = dict.move_to_front(input[i]);
res[i] = dist;
}
return res;
}
vector<uint8_t> MTF_decode(const vector<uint8_t>& input) {
deque<uint8_t> dict;
//Establish the list
for (size_t i = 0; i < 256; i++) {
dict.push_back(i);
}
vector<uint8_t> res(input.size());
for (size_t i = 0; i < input.size(); i++) {
res[i] = dict.at(input[i]);
dict.erase(dict.begin() + input[i]);
dict.push_front(res[i]);
}
return res;
}
const int MIN_LENGTH = 4;
const int MAX_LENGTH = 255;
// I'm lazy so that I put RLE here
// This method only encode 0 symbols after the MTF stage
vector<uint8_t> RLE_encode(const vector<uint8_t>& input) {
int zero_count = 0;
int rle_length = 0;
vector<uint8_t> encoded;
size_t size = input.size();
for (size_t i = 0; i < size; i++) {
if (zero_count == MIN_LENGTH) {
// in compression mode
while (i < size && 0 == input[i] && rle_length < MAX_LENGTH) {
rle_length++;
i++;
}
// Move back a position
--i;
//encode this length
encoded.push_back(rle_length);
//reset length
rle_length = 0;
zero_count = 0;
} else {
if (input[i] == 0) {
zero_count++;
} else {
zero_count = 0;
}
encoded.push_back(input[i]);
}
}
return encoded;
}
vector<uint8_t> RLE_decode(const vector<uint8_t>& input) {
int zero_count = 0;
vector<uint8_t> decoded;
for (size_t i = 0; i < input.size(); i++) {
if (zero_count == MIN_LENGTH) {
//decompression mode
//read one byte only
uint8_t length = input[i];
while (length--) {
decoded.push_back(0);
}
zero_count = 0;
} else {
if (input[i] == 0) {
zero_count++;
} else {
zero_count = 0;
}
decoded.push_back(input[i]);
}
}
return decoded;
}