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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
pub mod format;
mod baseline;
pub mod dictionary;
pub mod read;
pub mod rw;
mod util;
pub mod write;
mod predict;
pub mod probabilities;
use self::dictionary::{Dictionary, DictionaryFamily};
use self::probabilities::SymbolInfo;
use io::statistics::{
Bytes, BytesAndInstances, Instances, PerStaticKind, PerUserExtensibleKind, ProbabilityHistogram,
};
use binjs_shared::SharedString;
use std::cell::RefCell;
use std::rc::Rc;
const_with_str! {
const DEFAULT_WINDOW_LEN_FLOATS: usize = 0;
const DEFAULT_WINDOW_LEN_UNSIGNED_LONGS: usize = 0;
const DEFAULT_WINDOW_LEN_PROPERTY_KEYS: usize = 0;
const DEFAULT_WINDOW_LEN_IDENTIFIER_NAMES: usize = 8;
const DEFAULT_WINDOW_LEN_STRING_LITERALS: usize = 0;
const DEFAULT_WINDOW_LEN_LIST_LENGTHS: usize = 0;
mod arg_as_str;
}
#[derive(Clone)]
pub struct Options {
dictionaries: DictionaryFamily<SymbolInfo>,
content_lengths: Rc<RefCell<PerUserExtensibleKind<Bytes>>>,
content_instances: Rc<RefCell<PerUserExtensibleKind<Instances>>>,
probability_stats: Rc<RefCell<PerStaticKind<ProbabilityHistogram>>>,
content_window_len: PerUserExtensibleKind<usize>,
split_streams: bool,
}
impl Options {
pub fn new(
spec: &binjs_meta::spec::Spec,
mut dictionaries: DictionaryFamily<Instances>,
) -> Self {
use entropy::probabilities::InstancesToProbabilities;
let baseline = baseline::build(spec);
for dictionary in dictionaries.values_mut() {
*dictionary = dictionary.with_grammar_fallback(baseline.clone());
}
assert!(
!dictionaries.insert_baseline(baseline),
"The dictionary family MUST start without a definition for dictionary `*`"
);
let mut dictionaries = dictionaries.instances_to_probabilities("dictionary");
dictionaries
.enter_existing(&SharedString::from_str(""))
.unwrap();
Options {
dictionaries,
content_lengths: Rc::new(RefCell::new(PerUserExtensibleKind::default())),
content_instances: Rc::new(RefCell::new(PerUserExtensibleKind::default())),
probability_stats: Rc::new(RefCell::new(PerStaticKind::default())),
split_streams: false,
content_window_len: PerUserExtensibleKind {
floats: DEFAULT_WINDOW_LEN_FLOATS,
unsigned_longs: DEFAULT_WINDOW_LEN_UNSIGNED_LONGS,
property_keys: DEFAULT_WINDOW_LEN_PROPERTY_KEYS,
identifier_names: DEFAULT_WINDOW_LEN_IDENTIFIER_NAMES,
string_literals: DEFAULT_WINDOW_LEN_STRING_LITERALS,
list_lengths: DEFAULT_WINDOW_LEN_LIST_LENGTHS,
},
}
}
pub fn statistics_for_write(&self) -> impl std::fmt::Display {
let per_user_extensible_kind = {
let borrow_lengths = self.content_lengths.borrow();
let borrow_instances = self.content_instances.borrow();
PerUserExtensibleKind {
floats: BytesAndInstances::new(borrow_lengths.floats, borrow_instances.floats),
unsigned_longs: BytesAndInstances::new(
borrow_lengths.unsigned_longs,
borrow_instances.unsigned_longs,
),
property_keys: BytesAndInstances::new(
borrow_lengths.property_keys,
borrow_instances.property_keys,
),
identifier_names: BytesAndInstances::new(
borrow_lengths.identifier_names,
borrow_instances.identifier_names,
),
string_literals: BytesAndInstances::new(
borrow_lengths.string_literals,
borrow_instances.string_literals,
),
list_lengths: BytesAndInstances::new(
borrow_lengths.list_lengths,
borrow_instances.list_lengths,
),
}
};
let probability_stats = self.probability_stats.clone();
struct Statistics<A, B> {
bytes_and_instances_per_user_extensible_kind: A,
probability_histogram_per_static_kind: Rc<RefCell<B>>,
}
impl<A, B> std::fmt::Display for Statistics<A, B>
where
A: std::fmt::Display,
B: std::fmt::Display,
{
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.bytes_and_instances_per_user_extensible_kind
.fmt(formatter)?;
self.probability_histogram_per_static_kind
.borrow()
.fmt(formatter)?;
Ok(())
}
}
Statistics {
bytes_and_instances_per_user_extensible_kind: per_user_extensible_kind,
probability_histogram_per_static_kind: probability_stats,
}
}
pub fn with_split_streams(&mut self, value: bool) -> &mut Self {
self.split_streams = value;
self
}
}
use clap;
pub struct FormatProvider;
impl ::FormatProvider for FormatProvider {
fn subcommand<'a, 'b>(&self) -> clap::App<'a, 'b> {
use clap::*;
let validate_usize = |s: String| {
usize::from_str_radix(&s, 10)
.map(|_| ())
.map_err(|e| format!("{}", e))
};
SubCommand::with_name("entropy")
.about("(EXPERIMENTAL) Encode using entropy compression. This format produces a very good compression ratio in presence of a good dictionary.")
.arg(Arg::with_name("dictionary")
.help("(Recommended) path to external dictionary generated by binjs_generate_prediction_tables.")
.long("dictionary")
.takes_value(true)
.required(false)
)
.arg(Arg::with_name("split-streams")
.long("split-streams")
.help("If specified, dump all streams to the disk, for forensics purposes.")
.takes_value(false)
)
.arg(Arg::with_name("window-len-floats")
.long("window-len-floats")
.help("The length of the recall window for floats, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_FLOATS)
)
.arg(Arg::with_name("window-len-unsigned-longs")
.long("window-len-unsigned-longs")
.help("The length of the recall window for unsigned longs, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_UNSIGNED_LONGS)
)
.arg(Arg::with_name("window-len-property-keys")
.long("window-len-property-keys")
.help("The length of the recall window for property keys, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_PROPERTY_KEYS)
)
.arg(Arg::with_name("window-len-identifier-names")
.long("window-len-identifier-names")
.help("The length of the recall window for identifier names, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_IDENTIFIER_NAMES)
)
.arg(Arg::with_name("window-len-string-literals")
.long("window-len-string-literals")
.help("The length of the recall window for string literals, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_STRING_LITERALS)
)
.arg(Arg::with_name("window-len-list-lengths")
.long("window-len-list-lengths")
.help("The length of the recall window for list lengths, in indices.")
.takes_value(true)
.validator(validate_usize)
.default_value(arg_as_str::DEFAULT_WINDOW_LEN_LIST_LENGTHS)
)
}
fn handle_subcommand(
&self,
spec: &binjs_meta::spec::Spec,
matches: Option<&clap::ArgMatches>,
) -> Result<::Format, ::std::io::Error> {
let matches = matches.unwrap();
let dictionaries = match matches.value_of("dictionary") {
None => DictionaryFamily::new(),
Some(path) => {
let source = std::fs::File::open(&path).expect("Could not open dictionary");
let surface_dictionary: DictionaryFamily<Instances> =
bincode::deserialize_from(source).expect("Could not decode dictionary");
surface_dictionary
}
};
let split_streams = matches.is_present("split-streams");
let convert_usize = |key: &str| {
usize::from_str_radix(&matches.value_of(key).unwrap(), 10)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{}", e)))
};
let content_window_len = PerUserExtensibleKind {
floats: convert_usize("window-len-floats")?,
unsigned_longs: convert_usize("window-len-unsigned-longs")?,
property_keys: convert_usize("window-len-property-keys")?,
identifier_names: convert_usize("window-len-identifier-names")?,
string_literals: convert_usize("window-len-string-literals")?,
list_lengths: convert_usize("window-len-list-lengths")?,
};
Ok(::Format::Entropy {
options: Options {
content_lengths: Rc::new(RefCell::new(PerUserExtensibleKind::default())),
content_instances: Rc::new(RefCell::new(PerUserExtensibleKind::default())),
split_streams,
content_window_len,
..Options::new(spec, dictionaries)
},
})
}
}