Skip to main content

vortex_file/footer/
segment.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Range;
5
6use vortex_buffer::Alignment;
7use vortex_error::VortexError;
8use vortex_flatbuffers::footer as fb;
9
10/// The location of a segment within a Vortex file.
11///
12/// A segment is a contiguous block of bytes in a file that contains a part of the file's data.
13/// The `SegmentSpec` struct specifies the location and properties of a segment.
14#[derive(Clone, Copy, Debug)]
15pub struct SegmentSpec {
16    /// The byte offset of the segment from the start of the file.
17    pub offset: u64,
18    /// The length of the segment in bytes.
19    pub length: u32,
20    /// The memory alignment requirement of the segment.
21    pub alignment: Alignment,
22}
23
24impl SegmentSpec {
25    /// Returns the byte range of the segment within the file.
26    ///
27    /// The range starts at the segment's offset and extends for its length.
28    pub fn byte_range(&self) -> Range<u64> {
29        self.offset..self.offset + u64::from(self.length)
30    }
31}
32
33impl From<&SegmentSpec> for fb::SegmentSpec {
34    fn from(value: &SegmentSpec) -> Self {
35        fb::SegmentSpec::new(value.offset, value.length, value.alignment.exponent(), 0, 0)
36    }
37}
38
39impl TryFrom<&fb::SegmentSpec> for SegmentSpec {
40    type Error = VortexError;
41
42    fn try_from(value: &fb::SegmentSpec) -> Result<Self, Self::Error> {
43        Ok(Self {
44            offset: value.offset(),
45            length: value.length(),
46            // The alignment exponent comes from the file and may be corrupt, so validate it rather
47            // than panicking on a too-large shift (see issue #8819).
48            alignment: Alignment::try_from_untrusted_exponent(value.alignment_exponent())?,
49        })
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn rejects_out_of_range_alignment_exponent() {
59        // A fuzzed segment spec can declare an alignment exponent that would overflow a usize
60        // shift. Parsing it must return an error rather than panicking (see issue #8819).
61        let fb_spec = fb::SegmentSpec::new(0, 0, u8::MAX, 0, 0);
62        let err = SegmentSpec::try_from(&fb_spec).unwrap_err();
63        assert!(err.to_string().contains("too large"), "{err}");
64    }
65
66    #[test]
67    fn rejects_excessive_alignment_exponent() {
68        // A representable alignment can still cause an unreasonable allocation when a segment is
69        // copied to satisfy it.
70        let fb_spec = fb::SegmentSpec::new(0, 0, 17, 0, 0);
71        let err = SegmentSpec::try_from(&fb_spec).unwrap_err();
72        assert!(err.to_string().contains("exceeds"), "{err}");
73    }
74}