pub(crate) const KEY_ESCAPE: u8 = 0xff;
pub(crate) const KEY_PART_FINAL: u8 = 0x00;
pub(crate) const KEY_PART_MORE: u8 = 0x01;
pub(crate) const FILE_ID_NONE: u8 = 0x00;
pub(crate) const FILE_ID_SOME: u8 = 0x01;
pub(crate) const ROW_PK_CODEC_V1: u8 = 0x01;
pub(crate) const ROW_PK_UUID: u8 = 0x00;
pub(crate) const ROW_PK_INTEGER: u8 = 0x01;
pub(crate) const ROW_PK_STRING: u8 = 0x02;
pub(crate) const ROW_PK_BYTES: u8 = 0x03;
pub(crate) struct ScannedKeyPart {
pub(crate) value: ScannedKeyValue,
pub(crate) terminator: u8,
pub(crate) end: usize,
}
pub(crate) enum ScannedKeyValue {
Verbatim(core::ops::Range<usize>),
Unescaped(Vec<u8>),
}
pub(crate) enum KeyPartError {
Truncated,
EscapeTruncated,
UnknownEscape(u8),
}
#[inline]
pub(crate) fn scan_key_part(bytes: &[u8], start: usize) -> Result<ScannedKeyPart, KeyPartError> {
let tail = bytes.get(start..).ok_or(KeyPartError::Truncated)?;
let relative_zero = memchr::memchr(KEY_PART_FINAL, tail).ok_or(KeyPartError::Truncated)?;
let zero = start + relative_zero;
let escape = *bytes.get(zero + 1).ok_or(KeyPartError::EscapeTruncated)?;
if is_key_part_terminator(escape) {
return Ok(ScannedKeyPart {
value: ScannedKeyValue::Verbatim(start..zero),
terminator: escape,
end: zero + 2,
});
}
if escape != KEY_ESCAPE {
return Err(KeyPartError::UnknownEscape(escape));
}
scan_key_part_escaped(bytes, start, zero)
}
#[cold]
#[inline(never)]
fn scan_key_part_escaped(
bytes: &[u8],
start: usize,
first_zero: usize,
) -> Result<ScannedKeyPart, KeyPartError> {
let mut out = Vec::with_capacity(first_zero.saturating_sub(start).saturating_add(16));
out.extend_from_slice(&bytes[start..first_zero]);
out.push(KEY_PART_FINAL);
let mut segment_start = first_zero + 2;
loop {
let tail = bytes.get(segment_start..).ok_or(KeyPartError::Truncated)?;
let relative_zero = memchr::memchr(KEY_PART_FINAL, tail).ok_or(KeyPartError::Truncated)?;
let zero = segment_start + relative_zero;
let escape = *bytes.get(zero + 1).ok_or(KeyPartError::EscapeTruncated)?;
out.extend_from_slice(&bytes[segment_start..zero]);
if is_key_part_terminator(escape) {
return Ok(ScannedKeyPart {
value: ScannedKeyValue::Unescaped(out),
terminator: escape,
end: zero + 2,
});
}
if escape != KEY_ESCAPE {
return Err(KeyPartError::UnknownEscape(escape));
}
out.push(KEY_PART_FINAL);
segment_start = zero + 2;
}
}
pub(crate) const ROW_PK_UUID_BYTES: usize = 16;
pub(crate) const ROW_PK_INTEGER_BYTES: usize = 8;
pub(crate) fn is_key_part_terminator(byte: u8) -> bool {
matches!(byte, KEY_PART_FINAL | KEY_PART_MORE)
}
pub(crate) fn ordered_integer_from_i64(value: i64) -> u64 {
u64::from_be_bytes(value.to_be_bytes()) ^ (1_u64 << 63)
}
pub(crate) fn i64_from_ordered_integer(ordered: u64) -> i64 {
i64::from_be_bytes((ordered ^ (1_u64 << 63)).to_be_bytes())
}
pub(crate) fn write_row_pk(out: &mut Vec<u8>, row_pk: &crate::row_pk::RowPk) {
out.push(ROW_PK_CODEC_V1);
for (index, component) in row_pk.components.iter().enumerate() {
let terminator = if index + 1 == row_pk.components.len() {
KEY_PART_FINAL
} else {
KEY_PART_MORE
};
match component {
crate::row_pk::RowPkComponent::Uuid(bytes) => {
out.push(ROW_PK_UUID);
out.extend_from_slice(bytes);
out.push(terminator);
}
crate::row_pk::RowPkComponent::Integer(value) => {
out.push(ROW_PK_INTEGER);
out.extend_from_slice(&ordered_integer_from_i64(*value).to_be_bytes());
out.push(terminator);
}
crate::row_pk::RowPkComponent::String(value) => {
out.push(ROW_PK_STRING);
write_key_bytes(out, value.as_bytes(), terminator);
}
crate::row_pk::RowPkComponent::Bytes(value) => {
out.push(ROW_PK_BYTES);
write_key_bytes(out, value, terminator);
}
}
}
}
pub(crate) fn write_file_id(out: &mut Vec<u8>, file_id: Option<&str>) {
match file_id {
None => out.push(FILE_ID_NONE),
Some(file_id) => {
out.push(FILE_ID_SOME);
write_key_string(out, file_id, KEY_PART_FINAL);
}
}
}
pub(crate) fn write_key_string(out: &mut Vec<u8>, value: &str, terminator: u8) {
write_key_bytes(out, value.as_bytes(), terminator);
}
pub(crate) fn write_key_bytes(out: &mut Vec<u8>, value: &[u8], terminator: u8) {
for &byte in value {
if byte == KEY_PART_FINAL {
out.extend_from_slice(&[KEY_PART_FINAL, KEY_ESCAPE]);
} else {
out.push(byte);
}
}
out.extend_from_slice(&[KEY_PART_FINAL, terminator]);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::row_pk::{RowPk, RowPkComponent};
fn encoded_row_pk(components: Vec<RowPkComponent>) -> Vec<u8> {
let row_pk = RowPk::from_components(components.into_iter().collect())
.expect("golden row primary keys are non-empty");
let mut out = Vec::new();
write_row_pk(&mut out, &row_pk);
out
}
fn differential_corpus() -> Vec<Vec<u8>> {
let seeds = vec![
encoded_row_pk(vec![RowPkComponent::String("x".into())]),
encoded_row_pk(vec![RowPkComponent::String("a-b".into())]),
encoded_row_pk(vec![RowPkComponent::Integer(-1)]),
encoded_row_pk(vec![RowPkComponent::Uuid([7; 16])]),
encoded_row_pk(vec![RowPkComponent::Bytes(bytes::Bytes::from_static(
&[0, 0xff],
))]),
encoded_row_pk(vec![
RowPkComponent::String("a".into()),
RowPkComponent::Integer(7),
]),
encoded_row_pk(vec![
RowPkComponent::Uuid([0; 16]),
RowPkComponent::Bytes(bytes::Bytes::from_static(&[9])),
RowPkComponent::String("z".into()),
]),
];
let mut corpus = seeds.clone();
for seed in &seeds {
for len in 0..seed.len() {
corpus.push(seed[..len].to_vec());
}
for index in 0..seed.len() {
for replacement in [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x7f, 0xfe, 0xff] {
if seed[index] == replacement {
continue;
}
let mut mutated = seed.clone();
mutated[index] = replacement;
corpus.push(mutated);
}
}
}
corpus.extend([
vec![],
vec![ROW_PK_CODEC_V1],
vec![0x00],
vec![ROW_PK_CODEC_V1, ROW_PK_STRING, 0x00, 0x02],
vec![ROW_PK_CODEC_V1, ROW_PK_STRING, 0xff, 0x00, 0x00],
vec![ROW_PK_CODEC_V1, ROW_PK_STRING, 0x00, 0xff, 0x00, 0x00],
vec![ROW_PK_CODEC_V1, 0x05, 0x00, 0x00],
]);
corpus
}
fn render(decoded: Option<(RowPk, usize)>) -> String {
match decoded {
None => "rejected".to_string(),
Some((row_pk, offset)) => {
let mut out = Vec::new();
write_row_pk(&mut out, &row_pk);
format!(
"accepted off={offset} {}",
out.iter().map(|b| format!("{b:02x}")).collect::<String>()
)
}
}
}
#[test]
fn all_three_decoders_agree() {
let corpus = differential_corpus();
assert!(
corpus.len() > 700,
"differential corpus collapsed to {} cases",
corpus.len()
);
let mut accepted = 0usize;
for (index, input) in corpus.iter().enumerate() {
let head = render(crate::hot_state::head_decode_row_pk_probe(input));
let hot = render(crate::hot_state::hot_decode_row_pk_probe(input));
let tree = render(crate::tracked_state::tree_decode_row_pk_probe(input));
assert_eq!(
head, hot,
"tracked_head and hot disagree on case {index}: {input:02x?}"
);
assert_eq!(
head, tree,
"tracked_head and tracked_state disagree on case {index}: {input:02x?}"
);
if head != "rejected" {
accepted += 1;
}
}
assert!(
accepted >= 7,
"differential corpus accepted only {accepted} cases; it is no longer exercising decode"
);
}
#[test]
fn ordered_integer_round_trips() {
for value in [
i64::MIN,
i64::MIN + 1,
-2,
-1,
0,
1,
2,
i64::MAX - 1,
i64::MAX,
] {
assert_eq!(
i64_from_ordered_integer(ordered_integer_from_i64(value)),
value
);
}
assert_eq!(ordered_integer_from_i64(i64::MIN), 0);
assert_eq!(ordered_integer_from_i64(0), 1_u64 << 63);
assert_eq!(ordered_integer_from_i64(i64::MAX), u64::MAX);
}
#[test]
fn key_part_terminators_are_exactly_two() {
assert!(is_key_part_terminator(KEY_PART_FINAL));
assert!(is_key_part_terminator(KEY_PART_MORE));
for byte in [0x02u8, 0x03, 0x7f, KEY_ESCAPE] {
assert!(
!is_key_part_terminator(byte),
"{byte:#04x} is not a terminator"
);
}
}
#[test]
fn key_part_encoding_is_byte_pinned() {
let mut out = Vec::new();
write_key_string(&mut out, "ab", KEY_PART_FINAL);
assert_eq!(out, vec![b'a', b'b', 0x00, 0x00]);
let mut out = Vec::new();
write_key_string(&mut out, "ab", KEY_PART_MORE);
assert_eq!(out, vec![b'a', b'b', 0x00, 0x01]);
let mut out = Vec::new();
write_key_bytes(&mut out, b"a\0b", KEY_PART_FINAL);
assert_eq!(out, vec![b'a', 0x00, 0xff, b'b', 0x00, 0x00]);
let mut out = Vec::new();
write_key_bytes(&mut out, b"", KEY_PART_FINAL);
assert_eq!(out, vec![0x00, 0x00]);
}
#[test]
fn file_id_encoding_is_byte_pinned() {
let mut out = Vec::new();
write_file_id(&mut out, None);
assert_eq!(out, vec![0x00]);
let mut out = Vec::new();
write_file_id(&mut out, Some("f"));
assert_eq!(out, vec![0x01, b'f', 0x00, 0x00]);
}
#[test]
fn row_pk_encoding_is_byte_pinned() {
assert_eq!(
encoded_row_pk(vec![RowPkComponent::String("x".into())]),
vec![0x01, 0x02, b'x', 0x00, 0x00]
);
assert_eq!(
encoded_row_pk(vec![RowPkComponent::Bytes(bytes::Bytes::from_static(
&[0xaa]
))]),
vec![0x01, 0x03, 0xaa, 0x00, 0x00]
);
assert_eq!(
encoded_row_pk(vec![RowPkComponent::Uuid([7; 16])]),
[vec![0x01, 0x00], vec![7; 16], vec![0x00]].concat()
);
assert_eq!(
encoded_row_pk(vec![RowPkComponent::Integer(1)]),
vec![0x01, 0x01, 0x80, 0, 0, 0, 0, 0, 0, 0x01, 0x00]
);
assert_eq!(
encoded_row_pk(vec![
RowPkComponent::String("a".into()),
RowPkComponent::String("b".into()),
]),
vec![0x01, 0x02, b'a', 0x00, 0x01, 0x02, b'b', 0x00, 0x00]
);
}
#[test]
fn integer_components_encode_in_signed_order() {
let ordered = [i64::MIN, -2, -1, 0, 1, 2, i64::MAX]
.into_iter()
.map(|value| encoded_row_pk(vec![RowPkComponent::Integer(value)]))
.collect::<Vec<_>>();
let mut sorted = ordered.clone();
sorted.sort();
assert_eq!(ordered, sorted);
}
#[test]
fn escaped_strings_keep_lexical_order() {
let ordered = ["a", "a-", "a-b", "ab", "b"]
.into_iter()
.map(|value| encoded_row_pk(vec![RowPkComponent::String(value.into())]))
.collect::<Vec<_>>();
let mut sorted = ordered.clone();
sorted.sort();
assert_eq!(ordered, sorted);
}
}