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
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;
use std::{convert::TryFrom, fmt};
pub const ALGORITHM_ZSTD: u8 = 0;
/// Defines the compression types supported by documents & entries. Format when encoded is a single
/// byte, with the lowest two bits indicating the actual compression type. The upper 6 bits are
/// reserved for possible future compression formats. For now, the only allowed compression is
/// zstd, where the upper 6 bits are 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CompressType {
/// No compression
None,
/// Standard Compression
General,
/// Dictionary compression
Dict,
}
impl CompressType {
pub fn type_of(compress: &Compress) -> Self {
match compress {
Compress::None => CompressType::None,
Compress::General { .. } => CompressType::General,
Compress::Dict(_) => CompressType::Dict,
}
}
}
impl From<CompressType> for u8 {
fn from(val: CompressType) -> u8 {
match val {
CompressType::None => 0,
CompressType::General => 1,
CompressType::Dict => 2,
}
}
}
impl TryFrom<u8> for CompressType {
type Error = u8;
fn try_from(val: u8) -> Result<CompressType, u8> {
match val {
0 => Ok(CompressType::None),
1 => Ok(CompressType::General),
2 => Ok(CompressType::Dict),
_ => Err(val),
}
}
}
/// Compression settings for Documents and Entries.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Compress {
/// Don't compress by default.
None,
/// Compress using the given algorithm identifier and compression level.
General { algorithm: u8, level: u8 },
/// Compress using the provided dictionary object
Dict(Dictionary),
}
impl Compress {
/// Create a new general Zstd Compression setting.
pub fn new_zstd_general(level: u8) -> Self {
Compress::General {
algorithm: ALGORITHM_ZSTD,
level,
}
}
/// Create a new ZStandard dictionary with the given compression level.
pub fn new_zstd_dict(level: u8, dict: Vec<u8>) -> Self {
Compress::Dict(Dictionary::new_zstd(level, dict))
}
/// Attempt to compress the data. Failure occurs if this shouldn't compress, compression fails,
/// or the result is longer than the original. On failure, the buffer is discarded.
pub(crate) fn compress(&self, mut dest: Vec<u8>, src: &[u8]) -> Result<Vec<u8>, ()> {
match self {
Compress::None => Err(()),
Compress::General { level, .. } => {
let dest_len = dest.len();
let max_len = zstd_safe::compress_bound(src.len());
dest.resize(dest_len + max_len, 0);
match zstd_safe::compress(&mut dest[dest_len..], src, *level as i32) {
Ok(len) if len < src.len() => {
dest.truncate(dest_len + len);
Ok(dest)
}
_ => Err(()),
}
}
Compress::Dict(dict) => {
let dest_len = dest.len();
let max_len = zstd_safe::compress_bound(src.len());
dest.resize(dest_len + max_len, 0u8);
match &dict.0 {
DictionaryPrivate::Unknown { level, .. } => {
match zstd_safe::compress(&mut dest[dest_len..], src, *level as i32) {
Ok(len) if len < src.len() => {
dest.truncate(dest_len + len);
Ok(dest)
}
_ => Err(()),
}
}
DictionaryPrivate::Zstd { cdict, .. } => {
let mut ctx = zstd_safe::CCtx::create();
match ctx.compress_using_cdict(&mut dest[dest_len..], src, cdict) {
Ok(len) if len < src.len() => {
dest.truncate(dest_len + len);
Ok(dest)
}
_ => Err(()),
}
}
}
}
}
}
/// Attempt to decompress the data. Fails if the result in `dest` would be greater than
/// `max_size`, or if decompression fails.
pub(crate) fn decompress(
&self,
mut dest: Vec<u8>,
src: &[u8],
marker: CompressType,
extra_size: usize,
max_size: usize,
) -> Result<Vec<u8>> {
match marker {
CompressType::None => {
if dest.len() + src.len() + extra_size > max_size {
Err(Error::FailDecompress(format!(
"Decompressed length {} would be larger than maximum of {}",
dest.len() + src.len() + extra_size,
max_size
)))
} else {
dest.reserve(src.len() + extra_size);
dest.extend_from_slice(src);
Ok(dest)
}
}
CompressType::General => {
// Prep for decompressed data
let header_len = dest.len();
let Ok(Some(expected_len)) = zstd_safe::get_frame_content_size(src) else {
return Err(Error::FailDecompress("Compression frame header is invalid".into()));
};
if expected_len > (max_size - header_len) as u64 {
return Err(Error::FailDecompress(format!(
"Decompressed length {} would be larger than maximum of {}",
dest.len() + src.len(),
max_size
)));
}
let expected_len = expected_len as usize;
dest.reserve(expected_len + extra_size);
dest.resize(header_len + expected_len, 0u8);
// Safety: Immediately before this, we reserve enough space for the header and the
// expected length, so setting the length is OK. The decompress function overwrites
// data and returns the new valid length, so no data is uninitialized after this
// block completes. In the event of a failure, the vec is freed, so it is never
// returned in an invalid state.
let len = zstd_safe::decompress(&mut dest[header_len..], src).map_err(|e| {
Error::FailDecompress(format!("Failed Decompression, zstd error = {}", e))
})?;
dest.truncate(header_len + len);
Ok(dest)
}
CompressType::Dict => {
// Fetch dictionary
let ddict = if let Compress::Dict(Dictionary(DictionaryPrivate::Zstd {
ddict,
..
})) = self
{
ddict
} else {
return Err(Error::BadHeader(
"Header uses dictionary compression, but this has no matching supported dictionary".into()));
};
// Prep for decompressed data
let header_len = dest.len();
let Ok(Some(expected_len)) = zstd_safe::get_frame_content_size(src) else {
return Err(Error::FailDecompress("Compression frame header is invalid".into()));
};
if expected_len > (max_size - header_len) as u64 {
return Err(Error::FailDecompress(format!(
"Decompressed length {} would be larger than maximum of {}",
dest.len() + src.len(),
max_size
)));
}
let expected_len = expected_len as usize;
dest.reserve(expected_len + extra_size);
dest.resize(header_len + expected_len, 0u8);
// Safety: Immediately before this, we reserve enough space for the header and the
// expected length, so setting the length is OK. The decompress function overwrites
// data and returns the new valid length, so no data is uninitialized after this
// block completes. In the event of a failure, the vec is freed, so it is never
// returned in an invalid state.
let mut dctx = zstd_safe::DCtx::create();
let len = dctx
.decompress_using_ddict(&mut dest[header_len..], src, ddict)
.map_err(|e| {
Error::FailDecompress(format!(
"Failed Decompression, zstd error = {}",
e
))
})?;
dest.truncate(header_len + len);
Ok(dest)
}
}
}
}
impl std::default::Default for Compress {
fn default() -> Self {
Compress::General {
algorithm: ALGORITHM_ZSTD,
level: 3,
}
}
}
/// A ZStandard Compression dictionary.
///
/// A new dictionary can be created by providing the desired compression level and the dictionary
/// as a byte vector.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Dictionary(DictionaryPrivate);
impl Dictionary {
/// Create a new ZStandard compression dictionary.
pub fn new_zstd(level: u8, dict: Vec<u8>) -> Self {
let cdict = zstd_safe::create_cdict(&dict, level as i32);
let ddict = zstd_safe::create_ddict(&dict);
Self(DictionaryPrivate::Zstd {
level,
dict,
cdict,
ddict,
})
}
}
#[derive(Serialize, Deserialize)]
#[serde(from = "DictionarySerde", into = "DictionarySerde")]
enum DictionaryPrivate {
Unknown {
algorithm: u8,
level: u8,
dict: Vec<u8>,
},
Zstd {
level: u8,
dict: Vec<u8>,
cdict: zstd_safe::CDict<'static>,
ddict: zstd_safe::DDict<'static>,
},
}
// Struct used solely for serialization/deserialization
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct DictionarySerde {
algorithm: u8,
level: u8,
dict: ByteBuf,
}
impl Clone for DictionaryPrivate {
fn clone(&self) -> Self {
match self {
DictionaryPrivate::Unknown {
algorithm,
level,
dict,
} => DictionaryPrivate::Unknown {
algorithm: *algorithm,
level: *level,
dict: dict.clone(),
},
DictionaryPrivate::Zstd { level, dict, .. } => DictionaryPrivate::Zstd {
level: *level,
dict: dict.clone(),
cdict: zstd_safe::create_cdict(dict, *level as i32),
ddict: zstd_safe::create_ddict(dict),
},
}
}
}
impl fmt::Debug for DictionaryPrivate {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let (algorithm, level, dict) = match self {
DictionaryPrivate::Unknown {
algorithm,
level,
dict,
} => (algorithm, level, dict),
DictionaryPrivate::Zstd { level, dict, .. } => (&ALGORITHM_ZSTD, level, dict),
};
fmt.debug_struct("Dictionary")
.field("algorithm", algorithm)
.field("level", level)
.field("dict", dict)
.finish()
}
}
impl From<DictionarySerde> for DictionaryPrivate {
fn from(value: DictionarySerde) -> Self {
match value.algorithm {
ALGORITHM_ZSTD => {
let cdict = zstd_safe::create_cdict(&value.dict, value.level as i32);
let ddict = zstd_safe::create_ddict(&value.dict);
DictionaryPrivate::Zstd {
level: value.level,
dict: value.dict.into_vec(),
cdict,
ddict,
}
}
_ => DictionaryPrivate::Unknown {
algorithm: value.algorithm,
level: value.level,
dict: value.dict.into_vec(),
},
}
}
}
impl From<DictionaryPrivate> for DictionarySerde {
fn from(value: DictionaryPrivate) -> Self {
match value {
DictionaryPrivate::Unknown {
algorithm,
level,
dict,
} => Self {
algorithm,
level,
dict: ByteBuf::from(dict),
},
DictionaryPrivate::Zstd { level, dict, .. } => Self {
algorithm: ALGORITHM_ZSTD,
level,
dict: ByteBuf::from(dict),
},
}
}
}