tsdb_reader/chunks/
segment.rs1use crate::error::{Error, Result};
4use crate::varint;
5
6pub(crate) const MAGIC_CHUNKS: u32 = 0x85BD_40DD;
8pub const SEGMENT_HEADER_SIZE: usize = 8;
10pub(crate) const MAX_LEN_FIELD: usize = 5;
12
13#[derive(Debug)]
18pub struct ChunkSlice<'a> {
19 pub encoding: u8,
21 pub data: &'a [u8],
23 pub segment: u32,
25 pub offset: u32,
27 pub encoded_len: u32,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub(crate) struct RecordBounds {
35 pub encoding: usize,
36 pub data_start: usize,
37 pub data_end: usize,
38 pub crc_end: usize,
39 pub body_len: u32,
40}
41
42pub(crate) fn check_header(seg: &[u8], seq: u64) -> Result<()> {
44 if seg.len() < SEGMENT_HEADER_SIZE {
45 return Err(Error::format(format!(
46 "chunk segment {seq} too small: {} bytes",
47 seg.len()
48 )));
49 }
50 let magic = u32::from_be_bytes([seg[0], seg[1], seg[2], seg[3]]);
51 if magic != MAGIC_CHUNKS {
52 return Err(Error::format(format!(
53 "invalid chunk segment magic 0x{magic:08x} in segment {seq}"
54 )));
55 }
56 if seg[4] != 1 {
57 return Err(Error::Unsupported(format!(
58 "chunk segment format version {}",
59 seg[4]
60 )));
61 }
62 Ok(())
63}
64
65pub(crate) fn record_bounds(seg: &[u8], offset: u32) -> Result<RecordBounds> {
70 let start = offset as usize;
71 if start < SEGMENT_HEADER_SIZE {
72 return Err(Error::format(format!(
73 "chunk offset {start} points into the segment header"
74 )));
75 }
76 if start + MAX_LEN_FIELD > seg.len() {
77 return Err(Error::format(format!(
78 "chunk offset {start} leaves no room for the length field"
79 )));
80 }
81 let mut p = start;
82 let body_len = varint::uvarint(seg, &mut p)?;
83 if body_len == 0 {
84 return Err(Error::format("chunk length is zero"));
85 }
86 let body_len = u32::try_from(body_len)
87 .map_err(|_| Error::format(format!("chunk length {body_len} does not fit in u32")))?;
88 let data_start = p
89 .checked_add(1)
90 .ok_or_else(|| Error::format("chunk length overflow"))?;
91 let data_end = data_start
92 .checked_add(body_len as usize)
93 .ok_or_else(|| Error::format("chunk length overflow"))?;
94 let crc_end = data_end
95 .checked_add(4)
96 .ok_or_else(|| Error::format("chunk length overflow"))?;
97 if crc_end > seg.len() {
98 return Err(Error::format(format!(
99 "chunk at offset {start} is truncated: needs {crc_end} bytes, segment has {}",
100 seg.len()
101 )));
102 }
103 Ok(RecordBounds {
104 encoding: p,
105 data_start,
106 data_end,
107 crc_end,
108 body_len,
109 })
110}