Skip to main content

mito2/series_index/samples/
key_pages.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Independent 64 KiB frames for the logical key stream within one group.
16
17use crate::error::Result;
18use crate::series_index::samples::{invalid, require};
19
20pub(super) const PAGE_BYTES: usize = 64 * 1024;
21
22/// A u32 stored length per frame precedes the concatenated frames.
23/// Equal stored and logical lengths identify raw frames.
24pub(super) fn encode(keys: &[u8], compressor: &mut zstd::bulk::Compressor<'_>) -> Result<Vec<u8>> {
25    let count = keys.len().div_ceil(PAGE_BYTES);
26    let mut bytes = vec![0; count * 4];
27    for (i, raw) in keys.chunks(PAGE_BYTES).enumerate() {
28        let compressed = compressor
29            .compress(raw)
30            .map_err(|e| invalid(format!("sample key compression: {e}")))?;
31        let stored = if compressed.len() < raw.len() {
32            &compressed
33        } else {
34            raw
35        };
36        bytes[i * 4..i * 4 + 4].copy_from_slice(&(stored.len() as u32).to_le_bytes());
37        bytes.extend_from_slice(stored);
38    }
39    Ok(bytes)
40}
41
42pub(super) fn offsets(
43    directory: &[u8],
44    logical: u64,
45    physical: std::ops::Range<u64>,
46) -> Result<Vec<u64>> {
47    let mut offsets = Vec::with_capacity(directory.len() / 4 + 1);
48    let mut position = physical
49        .start
50        .checked_add(directory.len() as u64)
51        .ok_or_else(|| invalid("key directory overflow"))?;
52    let mut remaining = logical;
53    offsets.push(position);
54    let (entries, trailing) = directory.as_chunks::<4>();
55    require(trailing.is_empty(), "truncated key page directory entry")?;
56    for &entry in entries {
57        let size = u64::from(u32::from_le_bytes(entry));
58        let decoded = remaining.min(PAGE_BYTES as u64);
59        require(
60            size > 0 && size <= decoded,
61            "invalid stored key frame length",
62        )?;
63        remaining -= decoded;
64        position = position
65            .checked_add(size)
66            .filter(|p| *p <= physical.end)
67            .ok_or_else(|| invalid("key frame outside group"))?;
68        offsets.push(position);
69    }
70    require(
71        remaining == 0 && position == physical.end,
72        "invalid key page directory",
73    )?;
74    Ok(offsets)
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn raw_key_frame_has_only_length_and_payload() {
83        let expected = b"\x03\x00\x00\x00abc";
84        let encoded = encode(b"abc", &mut zstd::bulk::Compressor::new(1).unwrap()).unwrap();
85        assert_eq!(encoded, expected);
86        assert_eq!(offsets(&expected[..4], 3, 0..7).unwrap(), [4, 7]);
87        assert!(offsets(&[4, 0, 0, 0], 3, 0..7).is_err());
88        assert!(offsets(&expected[..4], 3, 0..6).is_err());
89    }
90}