oxirs-tdb 0.3.1

Apache Jena TDB/TDB2 compatible RDF storage engine with B+Tree indexes
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Unified compression module bringing together all compression capabilities
//!
//! This module provides a unified interface to all compression algorithms
//! supported by oxirs-tdb, with automatic algorithm selection based on
//! data characteristics.
//!
//! ## Supported Algorithms
//! - **LZ4**: Fast compression/decompression, moderate ratio
//! - **Zstandard**: High compression ratio, good speed
//! - **Brotli**: Web-optimized, excellent ratio for text
//! - **Snappy**: Extremely fast, moderate ratio
//! - **Prefix**: RDF URI prefix compression
//! - **Delta**: Delta encoding for sorted numeric data
//! - **Run-Length**: Run-length encoding for repeated values
//! - **Bitmap**: Bitmap compression for sparse data

use crate::error::{Result, TdbError};
use serde::{Deserialize, Serialize};

/// Compression strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionStrategy {
    /// Optimize for speed
    Speed,
    /// Balance speed and compression ratio
    Balanced,
    /// Optimize for compression ratio
    Ratio,
}

/// Compression algorithm identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum CompressionAlgorithm {
    /// No compression
    None = 0,
    /// LZ4 - fast compression
    Lz4 = 1,
    /// Zstandard - high compression ratio
    Zstd = 2,
    /// Brotli - web-optimized
    Brotli = 3,
    /// Snappy - extremely fast
    Snappy = 4,
    /// Prefix compression for URIs
    Prefix = 5,
    /// Delta encoding
    Delta = 6,
    /// Run-length encoding
    RunLength = 7,
    /// Bitmap compression
    Bitmap = 8,
}

/// Compression level (0-9, where 9 is maximum)
#[derive(Debug, Clone, Copy)]
pub struct CompressionLevel(u8);

impl CompressionLevel {
    /// Fastest compression (level 1)
    pub const FAST: Self = Self(1);
    /// Default compression (level 5)
    pub const DEFAULT: Self = Self(5);
    /// Best compression (level 9)
    pub const BEST: Self = Self(9);

    /// Create a new compression level
    pub fn new(level: u8) -> Self {
        Self(level.min(9))
    }

    /// Get the numeric level
    pub fn value(&self) -> u8 {
        self.0
    }
}

/// Compression statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressionStats {
    /// Algorithm used
    pub algorithm: CompressionAlgorithm,
    /// Original size in bytes
    pub original_size: usize,
    /// Compressed size in bytes
    pub compressed_size: usize,
    /// Compression ratio (compressed / original)
    pub ratio: f64,
    /// Compression time in microseconds
    pub compression_time_us: u64,
    /// Decompression time in microseconds (if measured)
    pub decompression_time_us: Option<u64>,
}

impl CompressionStats {
    /// Calculate compression ratio
    pub fn new(
        algorithm: CompressionAlgorithm,
        original_size: usize,
        compressed_size: usize,
        compression_time_us: u64,
    ) -> Self {
        let ratio = if original_size > 0 {
            compressed_size as f64 / original_size as f64
        } else {
            1.0
        };

        Self {
            algorithm,
            original_size,
            compressed_size,
            ratio,
            compression_time_us,
            decompression_time_us: None,
        }
    }

    /// Calculate space savings percentage
    pub fn savings_percent(&self) -> f64 {
        (1.0 - self.ratio) * 100.0
    }
}

/// Unified compression engine
pub struct UnifiedCompression {
    /// Default algorithm
    default_algorithm: CompressionAlgorithm,
    /// Default compression level
    default_level: CompressionLevel,
    /// Adaptive strategy
    strategy: CompressionStrategy,
}

impl UnifiedCompression {
    /// Create a new unified compression engine
    pub fn new() -> Self {
        Self {
            default_algorithm: CompressionAlgorithm::Zstd,
            default_level: CompressionLevel::DEFAULT,
            strategy: CompressionStrategy::Balanced,
        }
    }

    /// Set default algorithm
    pub fn with_algorithm(mut self, algorithm: CompressionAlgorithm) -> Self {
        self.default_algorithm = algorithm;
        self
    }

    /// Set default compression level
    pub fn with_level(mut self, level: CompressionLevel) -> Self {
        self.default_level = level;
        self
    }

    /// Set compression strategy
    pub fn with_strategy(mut self, strategy: CompressionStrategy) -> Self {
        self.strategy = strategy;
        self
    }

    /// Compress data using the default algorithm
    pub fn compress(&self, data: &[u8]) -> Result<Vec<u8>> {
        self.compress_with(data, self.default_algorithm, self.default_level)
    }

    /// Compress data with a specific algorithm
    pub fn compress_with(
        &self,
        data: &[u8],
        algorithm: CompressionAlgorithm,
        level: CompressionLevel,
    ) -> Result<Vec<u8>> {
        use std::time::Instant;

        let start = Instant::now();

        let compressed = match algorithm {
            CompressionAlgorithm::None => data.to_vec(),
            CompressionAlgorithm::Lz4 => self.compress_lz4(data)?,
            CompressionAlgorithm::Zstd => self.compress_zstd(data, level.value() as i32)?,
            CompressionAlgorithm::Brotli => self.compress_brotli(data, level.value() as u32)?,
            CompressionAlgorithm::Snappy => self.compress_snappy(data)?,
            _ => {
                return Err(TdbError::Other(format!(
                    "Algorithm {:?} not yet implemented",
                    algorithm
                )))
            }
        };

        Ok(compressed)
    }

    /// Decompress data
    pub fn decompress(&self, data: &[u8], algorithm: CompressionAlgorithm) -> Result<Vec<u8>> {
        match algorithm {
            CompressionAlgorithm::None => Ok(data.to_vec()),
            CompressionAlgorithm::Lz4 => self.decompress_lz4(data),
            CompressionAlgorithm::Zstd => self.decompress_zstd(data),
            CompressionAlgorithm::Brotli => self.decompress_brotli(data),
            CompressionAlgorithm::Snappy => self.decompress_snappy(data),
            _ => Err(TdbError::Other(format!(
                "Algorithm {:?} not yet implemented",
                algorithm
            ))),
        }
    }

    /// Select best algorithm for given data
    pub fn select_algorithm(&self, data: &[u8]) -> CompressionAlgorithm {
        // Heuristic-based selection
        match self.strategy {
            CompressionStrategy::Speed => CompressionAlgorithm::Snappy,
            CompressionStrategy::Balanced => {
                if data.len() < 1024 {
                    CompressionAlgorithm::Lz4
                } else {
                    CompressionAlgorithm::Zstd
                }
            }
            CompressionStrategy::Ratio => CompressionAlgorithm::Brotli,
        }
    }

    // Algorithm-specific implementations

    fn compress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
        oxiarc_lz4::compress(data)
            .map_err(|e| TdbError::Other(format!("LZ4 compression failed: {:?}", e)))
    }

    fn decompress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
        oxiarc_lz4::decompress(data, 100 * 1024 * 1024)
            .map_err(|e| TdbError::Other(format!("LZ4 decompression failed: {:?}", e)))
    }

    fn compress_zstd(&self, data: &[u8], level: i32) -> Result<Vec<u8>> {
        oxiarc_zstd::encode_all(data, level)
            .map_err(|e| TdbError::Other(format!("Zstd compression failed: {}", e)))
    }

    fn decompress_zstd(&self, data: &[u8]) -> Result<Vec<u8>> {
        oxiarc_zstd::decode_all(data)
            .map_err(|e| TdbError::Other(format!("Zstd decompression failed: {}", e)))
    }

    fn compress_brotli(&self, data: &[u8], level: u32) -> Result<Vec<u8>> {
        // Quality = `level`, default lgwin (22) matches the previous streaming
        // window size. The on-disk payload is a standard Brotli stream.
        oxiarc_brotli::compress(data, level)
            .map_err(|e| TdbError::Other(format!("Brotli compression failed: {}", e)))
    }

    fn decompress_brotli(&self, data: &[u8]) -> Result<Vec<u8>> {
        oxiarc_brotli::decompress(data)
            .map_err(|e| TdbError::Other(format!("Brotli decompression failed: {}", e)))
    }

    fn compress_snappy(&self, data: &[u8]) -> Result<Vec<u8>> {
        // Raw Snappy block format (no framing), matching the previous behavior.
        Ok(oxiarc_snappy::compress(data))
    }

    fn decompress_snappy(&self, data: &[u8]) -> Result<Vec<u8>> {
        oxiarc_snappy::decompress(data)
            .map_err(|e| TdbError::Other(format!("Snappy decompression failed: {}", e)))
    }

    /// Benchmark all algorithms on sample data
    pub fn benchmark(&self, data: &[u8]) -> Vec<CompressionStats> {
        let mut results = Vec::new();

        let algorithms = vec![
            CompressionAlgorithm::Lz4,
            CompressionAlgorithm::Zstd,
            CompressionAlgorithm::Brotli,
            CompressionAlgorithm::Snappy,
        ];

        for algo in algorithms {
            if let Ok(compressed) = self.compress_with(data, algo, CompressionLevel::DEFAULT) {
                let stats = CompressionStats::new(
                    algo,
                    data.len(),
                    compressed.len(),
                    0, // Time not measured in simple benchmark
                );
                results.push(stats);
            }
        }

        results
    }
}

impl Default for UnifiedCompression {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unified_compression_creation() {
        let _compression = UnifiedCompression::new();
    }

    #[test]
    fn test_compression_level() {
        assert_eq!(CompressionLevel::FAST.value(), 1);
        assert_eq!(CompressionLevel::DEFAULT.value(), 5);
        assert_eq!(CompressionLevel::BEST.value(), 9);

        let custom = CompressionLevel::new(7);
        assert_eq!(custom.value(), 7);

        // Test clamping
        let clamped = CompressionLevel::new(15);
        assert_eq!(clamped.value(), 9);
    }

    #[test]
    fn test_lz4_roundtrip() {
        let compression = UnifiedCompression::new();
        let data = b"Hello, World! This is a test of LZ4 compression.";

        let compressed = compression
            .compress_with(data, CompressionAlgorithm::Lz4, CompressionLevel::DEFAULT)
            .unwrap();

        // Note: For small data, compression may add overhead
        // The important thing is correctness of roundtrip

        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::Lz4)
            .unwrap();

        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_zstd_roundtrip() {
        let compression = UnifiedCompression::new();
        let data = b"Zstandard compression test data with some repetition repetition repetition";

        let compressed = compression
            .compress_with(data, CompressionAlgorithm::Zstd, CompressionLevel::DEFAULT)
            .unwrap();

        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::Zstd)
            .unwrap();

        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_snappy_roundtrip() {
        let compression = UnifiedCompression::new();
        let data = b"Snappy is designed for speed rather than maximum compression";

        let compressed = compression
            .compress_with(
                data,
                CompressionAlgorithm::Snappy,
                CompressionLevel::DEFAULT,
            )
            .unwrap();

        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::Snappy)
            .unwrap();

        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_brotli_roundtrip() {
        let compression = UnifiedCompression::new();
        let data = b"Brotli excels at compressing text and structured web content. ".repeat(20);

        let compressed = compression
            .compress_with(
                &data,
                CompressionAlgorithm::Brotli,
                CompressionLevel::DEFAULT,
            )
            .unwrap();

        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::Brotli)
            .unwrap();
        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_brotli_roundtrip_incompressible() {
        // Random/incompressible data must round-trip losslessly through the
        // standard Brotli on-disk format (no stored fallback).
        use scirs2_core::random::rng;
        use scirs2_core::RngExt;
        let mut r = rng();
        let data: Vec<u8> = (0..1500).map(|_| r.random_range(0..256) as u8).collect();

        let compression = UnifiedCompression::new();
        let compressed = compression
            .compress_with(
                &data,
                CompressionAlgorithm::Brotli,
                CompressionLevel::DEFAULT,
            )
            .unwrap();
        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::Brotli)
            .unwrap();
        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_algorithm_selection() {
        let compression = UnifiedCompression::new().with_strategy(CompressionStrategy::Speed);
        assert_eq!(
            compression.select_algorithm(b"test"),
            CompressionAlgorithm::Snappy
        );

        let compression = UnifiedCompression::new().with_strategy(CompressionStrategy::Ratio);
        assert_eq!(
            compression.select_algorithm(b"test"),
            CompressionAlgorithm::Brotli
        );
    }

    #[test]
    fn test_compression_stats() {
        let stats = CompressionStats::new(CompressionAlgorithm::Zstd, 1000, 500, 100);

        assert_eq!(stats.ratio, 0.5);
        assert_eq!(stats.savings_percent(), 50.0);
    }

    #[test]
    fn test_benchmark() {
        let compression = UnifiedCompression::new();
        let data = b"Sample data for benchmarking compression algorithms. ".repeat(10);

        let results = compression.benchmark(&data);

        assert!(results.len() >= 4); // At least 4 algorithms
        for result in &results {
            assert!(result.compressed_size > 0);
            assert!(result.compressed_size <= result.original_size);
        }
    }

    #[test]
    fn test_none_algorithm() {
        let compression = UnifiedCompression::new();
        let data = b"Test data";

        let compressed = compression
            .compress_with(data, CompressionAlgorithm::None, CompressionLevel::DEFAULT)
            .unwrap();

        assert_eq!(compressed, data);

        let decompressed = compression
            .decompress(&compressed, CompressionAlgorithm::None)
            .unwrap();

        assert_eq!(decompressed, data);
    }
}