Skip to main content

asset_io/
range.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Checked byte ranges.
15
16use crate::error::{Error, Result};
17
18/// A byte range `[offset, offset + len)` whose end is guaranteed not to overflow.
19///
20/// Fields are private; every constructor validates, so `end()` is always safe.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct ByteRange {
23    offset: u64,
24    len: u64,
25}
26
27impl ByteRange {
28    /// Create a range, failing if `offset + len` overflows `u64`.
29    pub fn new(offset: u64, len: u64) -> Result<Self> {
30        if offset.checked_add(len).is_none() {
31            return Err(Error::invalid_segment(
32                offset,
33                format!("range overflows u64 (len {len})"),
34            ));
35        }
36        Ok(Self { offset, len })
37    }
38
39    /// Construct from values the caller has already proven cannot overflow.
40    pub(crate) const fn raw(offset: u64, len: u64) -> Self {
41        Self { offset, len }
42    }
43
44    /// Start offset.
45    pub const fn offset(&self) -> u64 {
46        self.offset
47    }
48
49    /// Length in bytes.
50    pub const fn len(&self) -> u64 {
51        self.len
52    }
53
54    /// True if the range has zero length.
55    pub const fn is_empty(&self) -> bool {
56        self.len == 0
57    }
58
59    /// Exclusive end offset.
60    pub const fn end(&self) -> u64 {
61        self.offset + self.len
62    }
63
64    /// True if `other` lies entirely within `self`.
65    pub const fn contains(&self, other: &ByteRange) -> bool {
66        other.offset >= self.offset && other.end() <= self.end()
67    }
68
69    /// Sub-range at `rel_offset` from the start of `self`.
70    pub fn sub(&self, rel_offset: u64, len: u64) -> Result<ByteRange> {
71        let end = rel_offset.checked_add(len);
72        match end {
73            Some(e) if e <= self.len => Ok(ByteRange::raw(self.offset + rel_offset, len)),
74            _ => Err(Error::invalid_segment(
75                self.offset,
76                format!(
77                    "sub-range {rel_offset}+{len} exceeds range length {}",
78                    self.len
79                ),
80            )),
81        }
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    #[test]
90    fn rejects_overflow() {
91        assert!(ByteRange::new(u64::MAX, 1).is_err());
92        assert!(ByteRange::new(u64::MAX - 1, 1).is_ok());
93    }
94
95    #[test]
96    fn sub_and_contains() {
97        let r = ByteRange::new(10, 20).unwrap();
98        let s = r.sub(5, 10).unwrap();
99        assert_eq!((s.offset(), s.len(), s.end()), (15, 10, 25));
100        assert!(r.contains(&s));
101        assert!(r.sub(15, 6).is_err());
102        assert!(r.sub(u64::MAX, 2).is_err());
103    }
104}