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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#[macro_use]
extern crate failure_derive;
pub use crate::lz_dict::LZDict;
use std::io;
pub mod lz_dict;
pub mod crc32;
pub mod murmur3;
#[derive(Debug, Fail)]
pub enum LZJDError {
#[fail(display = "IO error: {}", err)]
Io {
#[cause]
err: io::Error,
},
#[fail(display = "Decode error: {}", err)]
Base64 {
#[cause]
err: base64::DecodeError,
},
#[fail(display = "Bincode error: {}", err)]
Bincode {
#[cause]
err: bincode::Error,
},
#[fail(display = "Error: {}", msg)]
Msg { msg: String },
}
impl From<base64::DecodeError> for LZJDError {
fn from(err: base64::DecodeError) -> Self {
LZJDError::Base64 { err }
}
}
impl From<bincode::Error> for LZJDError {
fn from(err: bincode::Error) -> Self {
LZJDError::Bincode { err }
}
}
impl From<std::io::Error> for LZJDError {
fn from(err: std::io::Error) -> Self {
LZJDError::Io { err }
}
}
impl<'a> From<&'a str> for LZJDError {
fn from(msg: &'a str) -> Self {
LZJDError::Msg {
msg: msg.to_owned(),
}
}
}
pub type Result<T> = std::result::Result<T, LZJDError>;
#[cfg(test)]
mod tests {
use crate::crc32::CRC32BuildHasher;
use crate::*;
use std::f64::EPSILON;
#[test]
fn test_optimized_dist() {
let build_hasher = CRC32BuildHasher;
let a = b"THIS IS A TEST SEQUENCE";
let b = b"THIS IS A TEST SEQUENCE";
let c = b"totally_different";
let d = b"THIS IS A DIFFERENT TEST SEQUENCE";
let dict_a = LZDict::from_bytes_stream_lz78(a.iter().cloned(), &build_hasher);
let dict_b = LZDict::from_bytes_stream_lz78(b.iter().cloned(), &build_hasher);
let dict_c = LZDict::from_bytes_stream_lz78(c.iter().cloned(), &build_hasher);
let dict_d = LZDict::from_bytes_stream_lz78(d.iter().cloned(), &build_hasher);
let dist = dict_a.dist(&dict_b);
assert!(
dist.abs() < EPSILON,
"Distance of equal sequences (a and b) should equal 0, was {}",
dist
);
let dist = dict_a.dist(&dict_c);
assert!(
(1. - dist).abs() < EPSILON,
"Distance of totally different sequences (a and c) should equal 1, was {}",
dist
);
let dist = dict_a.dist(&dict_d);
assert!(
(0.409_090_909_090_909_06 - dist).abs() < EPSILON,
"Distance of a and d should equal 0.40909090909090906, was {}",
dist
);
assert!(
(dict_a.dist(&dict_d) - dict_d.dist(&dict_a)).abs() < EPSILON,
"Distance of a and d should be equal to distance of d and a"
);
}
}