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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Shared types for LUT-based SIMD codecs
/// Character range in dictionary (contiguous ASCII sequence)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(super) struct CharRange {
pub(super) start_idx: u8, // First index in this range
pub(super) end_idx: u8, // Last index (inclusive)
pub(super) start_char: u8, // First ASCII character
pub(super) offset: i8, // char = index + offset
}
/// Range-reduction strategy based on number of ranges
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(super) enum RangeStrategy {
Simple, // 1 range, direct offset
Small, // 2 ranges, single subs
SmallMulti, // 3-5 ranges, subs + 1 cmp + blend
Medium, // 6-8 ranges, 2-3 thresholds
Large, // 9-12 ranges, 3-4 thresholds
VeryLarge, // 13-16 ranges, 4-5 thresholds
}
/// Range-reduction metadata for SSE/AVX2 encoding
#[cfg(target_arch = "x86_64")]
#[derive(Debug, Clone)]
pub(super) struct RangeInfo {
pub(super) ranges: Vec<CharRange>,
pub(super) offset_lut: [i8; 16], // pshufb lookup table
pub(super) strategy: RangeStrategy, // Encoding strategy
// Single threshold (for 2 ranges)
pub(super) subs_threshold: u8, // For _mm_subs_epu8
pub(super) cmp_value: Option<u8>, // For _mm_cmplt_epi8 (if needed)
pub(super) override_val: Option<u8>, // For _mm_blendv_epi8 (if needed)
// Multiple thresholds (for 6-16 ranges)
pub(super) thresholds: Vec<u8>, // Ordered thresholds for binary tree
pub(super) cmp_values: Vec<u8>, // Comparison values for each threshold
}
#[cfg(target_arch = "x86_64")]
impl RangeInfo {
/// Build range-reduction metadata for 1-5 contiguous ranges
///
/// Note: 6+ range support is not implemented (would need multi-threshold
/// compression which doesn't fit in 16-byte LUT). Falls back to scalar.
pub(super) fn build_multi_range(ranges: &[CharRange]) -> Option<Self> {
let num_ranges = ranges.len();
// Reject if >5 ranges (6+ range multi-threshold not implemented)
// Also reject if 0 ranges
if num_ranges == 0 || num_ranges > 5 {
return None;
}
// Dispatch based on range count
match num_ranges {
1 => Self::build_single_range(ranges),
2 => Self::build_two_ranges(ranges),
3..=5 => Self::build_small_multirange(ranges),
_ => None,
}
}
/// Build for single range (no reduction needed)
fn build_single_range(ranges: &[CharRange]) -> Option<Self> {
let range = ranges[0];
// Single contiguous range: just use offset directly
let mut offset_lut = [0i8; 16];
offset_lut.iter_mut().for_each(|val| *val = range.offset);
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::Simple,
subs_threshold: 0, // No subtraction needed
cmp_value: None,
override_val: None,
thresholds: Vec::new(),
cmp_values: Vec::new(),
})
}
/// Build for two ranges (base32 case)
fn build_two_ranges(ranges: &[CharRange]) -> Option<Self> {
let range0 = ranges[0];
let range1 = ranges[1];
// Use boundary of first range as threshold
let subs_threshold = range0.end_idx;
// Build offset LUT for pshufb
let mut offset_lut = [0i8; 16];
// After subtraction:
// range0 indices → 0
// range1 indices → [1..=(range1.end_idx - range0.end_idx)]
offset_lut[0] = range0.offset;
// Fill remaining slots with range1 offset
let range1_compressed_len = ((range1.end_idx - range0.end_idx) as usize).min(15);
offset_lut
.iter_mut()
.skip(1)
.take(range1_compressed_len)
.for_each(|val| *val = range1.offset);
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::Small,
subs_threshold,
cmp_value: None, // No comparison needed for 2 ranges
override_val: None, // No override needed for 2 ranges
thresholds: Vec::new(),
cmp_values: Vec::new(),
})
}
/// Build for 3-5 ranges (base64-style)
///
/// Uses pshufb for index-to-offset lookup, which only supports 16 entries.
/// This limits which dictionaries can use this path.
fn build_small_multirange(ranges: &[CharRange]) -> Option<Self> {
// Strategy: Use boundary of second-largest range as threshold
// This maps the two largest ranges to 0, distinguish via comparison
// Find two largest ranges by length
let mut sorted_ranges: Vec<_> = ranges.iter().enumerate().collect();
sorted_ranges
.sort_by_key(|(_, r)| std::cmp::Reverse((r.end_idx - r.start_idx + 1) as usize));
let (largest_idx, largest_range) = sorted_ranges[0];
let (second_largest_idx, second_largest_range) = sorted_ranges[1];
// Threshold: end of second-largest range
// For base64: ranges[1] ('a'-'z', indices 26-51) is second-largest
let subs_threshold = second_largest_range.end_idx;
// Validate: after subtracting threshold, all indices must fit in 16-entry LUT
// max_compressed_idx = last_dict_idx - threshold
let last_dict_idx = ranges.last()?.end_idx;
let max_compressed_idx = last_dict_idx.saturating_sub(subs_threshold);
if max_compressed_idx >= 16 {
// Dictionary doesn't fit in 16-byte pshufb LUT
// Example: geohash has threshold=9, last_idx=31, compressed=22 > 16
return None;
}
// After subtraction, both large ranges map to 0 or near-0
// Comparison value: distinguish the two large ranges
let cmp_value = if largest_idx < second_largest_idx {
// Largest comes first in dictionary
second_largest_range.start_idx
} else {
// Second-largest comes first
largest_range.start_idx
};
// Build offset LUT
let mut offset_lut = [0i8; 16];
// Second-largest range stays at compressed index 0
offset_lut[0] = second_largest_range.offset;
let mut compressed_idx = 1;
// Map tail ranges (those after threshold)
for range in ranges {
if range.start_idx > subs_threshold {
let range_len = (range.end_idx - range.start_idx + 1) as usize;
let fill_count = range_len.min(16 - compressed_idx);
offset_lut
.iter_mut()
.skip(compressed_idx)
.take(fill_count)
.for_each(|val| *val = range.offset);
compressed_idx += range_len;
if compressed_idx >= 15 {
break;
}
}
}
// Largest range gets override via blendv
let override_idx = compressed_idx.min(15);
offset_lut[override_idx] = largest_range.offset;
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::SmallMulti,
subs_threshold,
cmp_value: Some(cmp_value),
override_val: Some(override_idx as u8),
thresholds: Vec::new(),
cmp_values: Vec::new(),
})
}
/// Build for 6-8 ranges (medium multirange with 2-3 thresholds)
#[allow(dead_code)]
fn build_medium_multirange(ranges: &[CharRange]) -> Option<Self> {
assert!(ranges.len() >= 6 && ranges.len() <= 8);
// Select thresholds using balanced binary partitioning
let thresholds = Self::select_thresholds_medium(ranges);
let cmp_values: Vec<u8> = thresholds.iter().map(|&t| t + 1).collect();
// Build hierarchical LUT
let offset_lut = Self::build_hierarchical_lut_medium(ranges, &thresholds);
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::Medium,
subs_threshold: 0, // Unused for multi-threshold
cmp_value: None,
override_val: None,
thresholds,
cmp_values,
})
}
/// Select thresholds for 6-8 ranges (2-3 thresholds needed)
#[allow(dead_code)]
fn select_thresholds_medium(ranges: &[CharRange]) -> Vec<u8> {
let num_ranges = ranges.len();
let mut thresholds = Vec::new();
// First threshold: split ranges roughly in half
let mid_idx = num_ranges / 2;
if mid_idx > 0 && mid_idx < num_ranges {
thresholds.push(ranges[mid_idx - 1].end_idx);
}
// Second threshold: split lower half
if mid_idx > 1 {
let lower_mid = mid_idx / 2;
if lower_mid > 0 {
thresholds.push(ranges[lower_mid - 1].end_idx);
}
}
// Third threshold: split upper half (if 7-8 ranges)
if num_ranges > 6 {
let upper_mid = mid_idx + (num_ranges - mid_idx) / 2;
if upper_mid > mid_idx && upper_mid < num_ranges {
thresholds.push(ranges[upper_mid - 1].end_idx);
}
}
thresholds.sort();
thresholds
}
/// Build hierarchical LUT for 6-8 ranges
#[allow(dead_code)]
fn build_hierarchical_lut_medium(ranges: &[CharRange], _thresholds: &[u8]) -> [i8; 16] {
let mut lut = [0i8; 16];
let mut compressed_idx = 0usize;
// Assign compressed indices by traversing ranges
for range in ranges {
let range_len = (range.end_idx - range.start_idx + 1) as usize;
let fill_count = range_len.min(16 - compressed_idx);
lut.iter_mut()
.skip(compressed_idx)
.take(fill_count)
.for_each(|val| *val = range.offset);
compressed_idx += range_len;
if compressed_idx >= 16 {
break;
}
}
lut
}
/// Build for 9-12 ranges (large multirange with 3-4 thresholds)
#[allow(dead_code)]
fn build_large_multirange(ranges: &[CharRange]) -> Option<Self> {
assert!(ranges.len() >= 9 && ranges.len() <= 12);
let thresholds = Self::select_thresholds_large(ranges);
let cmp_values: Vec<u8> = thresholds.iter().map(|&t| t + 1).collect();
let offset_lut = Self::build_hierarchical_lut_large(ranges, &thresholds);
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::Large,
subs_threshold: 0,
cmp_value: None,
override_val: None,
thresholds,
cmp_values,
})
}
/// Select thresholds for 9-12 ranges (3-4 thresholds)
#[allow(dead_code)]
fn select_thresholds_large(ranges: &[CharRange]) -> Vec<u8> {
let mut thresholds = Vec::new();
// Recursive balanced partitioning for 3-4 levels
fn partition_ranges(ranges: &[CharRange], depth: usize, thresholds: &mut Vec<u8>) {
if ranges.is_empty() || depth >= 4 {
return;
}
let mid_idx = ranges.len() / 2;
if mid_idx > 0 && mid_idx < ranges.len() {
thresholds.push(ranges[mid_idx - 1].end_idx);
partition_ranges(&ranges[..mid_idx], depth + 1, thresholds);
partition_ranges(&ranges[mid_idx..], depth + 1, thresholds);
}
}
partition_ranges(ranges, 0, &mut thresholds);
thresholds.sort();
thresholds.dedup();
thresholds
}
/// Build hierarchical LUT for 9-12 ranges
#[allow(dead_code)]
fn build_hierarchical_lut_large(ranges: &[CharRange], _thresholds: &[u8]) -> [i8; 16] {
let mut lut = [0i8; 16];
let mut compressed_idx = 0usize;
for range in ranges {
let range_len = (range.end_idx - range.start_idx + 1) as usize;
let fill_count = range_len.min(16 - compressed_idx);
lut.iter_mut()
.skip(compressed_idx)
.take(fill_count)
.for_each(|val| *val = range.offset);
compressed_idx += range_len;
if compressed_idx >= 16 {
break;
}
}
lut
}
/// Build for 13-16 ranges (very large multirange with 4-5 thresholds)
#[allow(dead_code)]
fn build_very_large_multirange(ranges: &[CharRange]) -> Option<Self> {
assert!(ranges.len() >= 13 && ranges.len() <= 16);
let thresholds = Self::select_thresholds_very_large(ranges);
let cmp_values: Vec<u8> = thresholds.iter().map(|&t| t + 1).collect();
let offset_lut = Self::build_hierarchical_lut_very_large(ranges, &thresholds);
Some(RangeInfo {
ranges: ranges.to_vec(),
offset_lut,
strategy: RangeStrategy::VeryLarge,
subs_threshold: 0,
cmp_value: None,
override_val: None,
thresholds,
cmp_values,
})
}
/// Select thresholds for 13-16 ranges (4-5 thresholds)
#[allow(dead_code)]
fn select_thresholds_very_large(ranges: &[CharRange]) -> Vec<u8> {
let mut thresholds = Vec::new();
fn partition_ranges(ranges: &[CharRange], depth: usize, thresholds: &mut Vec<u8>) {
if ranges.is_empty() || depth >= 5 {
return;
}
let mid_idx = ranges.len() / 2;
if mid_idx > 0 && mid_idx < ranges.len() {
thresholds.push(ranges[mid_idx - 1].end_idx);
partition_ranges(&ranges[..mid_idx], depth + 1, thresholds);
partition_ranges(&ranges[mid_idx..], depth + 1, thresholds);
}
}
partition_ranges(ranges, 0, &mut thresholds);
thresholds.sort();
thresholds.dedup();
thresholds
}
/// Build hierarchical LUT for 13-16 ranges
#[allow(dead_code)]
fn build_hierarchical_lut_very_large(ranges: &[CharRange], _thresholds: &[u8]) -> [i8; 16] {
let mut lut = [0i8; 16];
let mut compressed_idx = 0usize;
for range in ranges {
let range_len = (range.end_idx - range.start_idx + 1) as usize;
let fill_count = range_len.min(16 - compressed_idx);
lut.iter_mut()
.skip(compressed_idx)
.take(fill_count)
.for_each(|val| *val = range.offset);
compressed_idx += range_len;
if compressed_idx >= 16 {
break;
}
}
lut
}
}