compress.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. if n > MAX {
  33. n = MAX;
  34. }
  35. if n < MIN {
  36. n = MIN;
  37. }
  38. match d.decompress(data, n) {
  39. Ok(res) => out = res,
  40. Err(err) => {
  41. crate::log::debug!("Failed to decompress: {}", err);
  42. }
  43. }
  44. }
  45. });
  46. out
  47. }