lsm_tree/value.rs
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
// Copyright (c) 2024-present, fjall-rs
// This source code is licensed under both the Apache 2.0 and MIT License
// (found in the LICENSE-* files in the repository)
use crate::{
coding::{Decode, DecodeError, Encode, EncodeError},
key::InternalKey,
segment::block::ItemSize,
Slice,
};
use std::io::{Read, Write};
use varint_rs::{VarintReader, VarintWriter};
/// User defined key
pub type UserKey = Slice;
/// User defined data (blob of bytes)
#[allow(clippy::module_name_repetitions)]
pub type UserValue = Slice;
/// Sequence number - a monotonically increasing counter
///
/// Values with the same seqno are part of the same batch.
///
/// A value with a higher sequence number shadows an item with the
/// same key and lower sequence number. This enables MVCC.
///
/// Stale items are lazily garbage-collected during compaction.
pub type SeqNo = u64;
/// Value type (regular value or tombstone)
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(clippy::module_name_repetitions)]
pub enum ValueType {
/// Existing value
Value,
/// Deleted value
Tombstone,
/// "Weak" deletion (a.k.a. `SingleDelete` in `RocksDB`)
WeakTombstone,
}
impl TryFrom<u8> for ValueType {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Value),
1 => Ok(Self::Tombstone),
2 => Ok(Self::WeakTombstone),
_ => Err(()),
}
}
}
impl From<ValueType> for u8 {
fn from(value: ValueType) -> Self {
match value {
ValueType::Value => 0,
ValueType::Tombstone => 1,
ValueType::WeakTombstone => 2,
}
}
}
/// Internal representation of KV pairs
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Eq, PartialEq)]
pub struct InternalValue {
/// Internal key
pub key: InternalKey,
/// User-defined value - an arbitrary byte array
///
/// Supports up to 2^32 bytes
pub value: UserValue,
}
impl InternalValue {
/// Creates a new [`Value`].
///
/// # Panics
///
/// Panics if the key length is empty or greater than 2^16, or the value length is greater than 2^32.
pub fn new<V: Into<UserValue>>(key: InternalKey, value: V) -> Self {
let value = value.into();
assert!(!key.user_key.is_empty(), "key may not be empty");
assert!(
u32::try_from(value.len()).is_ok(),
"values can be 2^32 bytes in length"
);
Self { key, value }
}
/// Creates a new [`Value`].
///
/// # Panics
///
/// Panics if the key length is empty or greater than 2^16, or the value length is greater than 2^32.
pub fn from_components<K: Into<UserKey>, V: Into<UserValue>>(
user_key: K,
value: V,
seqno: SeqNo,
value_type: ValueType,
) -> Self {
let key = InternalKey::new(user_key, seqno, value_type);
Self::new(key, value)
}
/// Creates a new tombstone.
///
/// # Panics
///
/// Panics if the key length is empty or greater than 2^16.
pub fn new_tombstone<K: Into<UserKey>>(key: K, seqno: u64) -> Self {
let key = key.into();
let key = InternalKey::new(key, seqno, ValueType::Tombstone);
Self::new(key, vec![])
}
/// Creates a new weak tombstone.
///
/// # Panics
///
/// Panics if the key length is empty or greater than 2^16.
pub fn new_weak_tombstone<K: Into<UserKey>>(key: K, seqno: u64) -> Self {
let key = key.into();
let key = InternalKey::new(key, seqno, ValueType::WeakTombstone);
Self::new(key, vec![])
}
#[doc(hidden)]
#[must_use]
pub fn is_tombstone(&self) -> bool {
self.key.is_tombstone()
}
}
impl ItemSize for InternalValue {
fn size(&self) -> usize {
std::mem::size_of::<SeqNo>()
+ std::mem::size_of::<ValueType>()
+ self.key.user_key.len()
+ self.value.len()
}
}
impl std::fmt::Debug for InternalValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{:?} => {:?}",
self.key,
if self.value.len() >= 64 {
format!("[ ... {} bytes ]", self.value.len())
} else {
format!("{:?}", self.value)
}
)
}
}
impl Encode for InternalValue {
fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError> {
self.key.encode_into(writer)?;
// NOTE: Only write value len + value if we are actually a value
if !self.is_tombstone() {
// NOTE: We know values are limited to 32-bit length
#[allow(clippy::cast_possible_truncation)]
writer.write_u32_varint(self.value.len() as u32)?;
writer.write_all(&self.value)?;
}
Ok(())
}
}
impl Decode for InternalValue {
fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let key = InternalKey::decode_from(reader)?;
if key.is_tombstone() {
Ok(Self {
key,
value: vec![].into(),
})
} else {
// NOTE: Only read value if we are actually a value
let value_len = reader.read_u32_varint()?;
let mut value = vec![0; value_len as usize];
reader.read_exact(&mut value)?;
Ok(Self {
key,
value: value.into(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use test_log::test;
#[test]
fn pik_cmp_user_key() {
let a = InternalKey::new(*b"a", 0, ValueType::Value);
let b = InternalKey::new(*b"b", 0, ValueType::Value);
assert!(a < b);
}
#[test]
fn pik_cmp_seqno() {
let a = InternalKey::new(*b"a", 0, ValueType::Value);
let b = InternalKey::new(*b"a", 1, ValueType::Value);
assert!(a > b);
}
#[test]
fn value_raw() -> crate::Result<()> {
// Create an empty Value instance
let value =
InternalValue::from_components(vec![1, 2, 3], vec![3, 2, 1], 1, ValueType::Value);
#[rustfmt::skip]
let bytes = [
// Seqno
1,
// Type
0,
// User key
3, 1, 2, 3,
// User value
3, 3, 2, 1,
];
// Deserialize the empty Value
let deserialized = InternalValue::decode_from(&mut Cursor::new(bytes))?;
// Check if deserialized Value is equivalent to the original empty Value
assert_eq!(value, deserialized);
Ok(())
}
#[test]
fn value_empty_value() -> crate::Result<()> {
// Create an empty Value instance
let value = InternalValue::from_components(vec![1, 2, 3], vec![], 42, ValueType::Value);
// Serialize the empty Value
let mut serialized = Vec::new();
value.encode_into(&mut serialized)?;
// Deserialize the empty Value
let deserialized = InternalValue::decode_from(&mut &serialized[..])?;
// Check if deserialized Value is equivalent to the original empty Value
assert_eq!(value, deserialized);
Ok(())
}
#[test]
fn value_with_value() -> crate::Result<()> {
// Create an empty Value instance
let value = InternalValue::from_components(
vec![1, 2, 3],
vec![6, 2, 6, 2, 7, 5, 7, 8, 98],
42,
ValueType::Value,
);
// Serialize the empty Value
let mut serialized = Vec::new();
value.encode_into(&mut serialized)?;
// Deserialize the empty Value
let deserialized = InternalValue::decode_from(&mut &serialized[..])?;
// Check if deserialized Value is equivalent to the original empty Value
assert_eq!(value, deserialized);
Ok(())
}
}