compress.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use std::cell::RefCell;
  2. use zstd::block::{Compressor, Decompressor};
  3. thread_local! {
  4. static COMPRESSOR: RefCell<Compressor> = RefCell::new(Compressor::new());
  5. static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());
  6. }
  7. /// The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
  8. /// which is currently 22. Levels >= 20
  9. /// Default level is ZSTD_CLEVEL_DEFAULT==3.
  10. /// value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT
  11. pub fn compress(data: &[u8], level: i32) -> Vec<u8> {
  12. let mut out = Vec::new();
  13. COMPRESSOR.with(|c| {
  14. if let Ok(mut c) = c.try_borrow_mut() {
  15. match c.compress(data, level) {
  16. Ok(res) => out = res,
  17. Err(err) => {
  18. crate::log::debug!("Failed to compress: {}", err);
  19. }
  20. }
  21. }
  22. });
  23. out
  24. }
  25. pub fn decompress(data: &[u8]) -> Vec<u8> {
  26. let mut out = Vec::new();
  27. DECOMPRESSOR.with(|d| {
  28. if let Ok(mut d) = d.try_borrow_mut() {
  29. const MAX: usize = 1024 * 1024 * 64;
  30. const MIN: usize = 1024 * 1024;
  31. let mut n = 30 * data.len();
  32. n = n.clamp(MIN, MAX);
  33. match d.decompress(data, n) {
  34. Ok(res) => out = res,
  35. Err(err) => {
  36. crate::log::debug!("Failed to decompress: {}", err);
  37. }
  38. }
  39. }
  40. });
  41. out
  42. }