shadow_rs/utility/
stream_len.rs

1use std::io::{Seek, SeekFrom};
2
3pub trait StreamLen {
4    /// Backport of std::io::Seek::stream_len from Rust nightly.
5    fn stream_len_bp(&mut self) -> std::io::Result<u64>;
6}
7
8impl<T> StreamLen for T
9where
10    T: Seek,
11{
12    fn stream_len_bp(&mut self) -> std::io::Result<u64> {
13        let current = self.stream_position()?;
14        let end = self.seek(SeekFrom::End(0))?;
15        if current != end {
16            self.seek(SeekFrom::Start(current))?;
17        }
18        Ok(end)
19    }
20}
21
22#[cfg(test)]
23mod tests {
24    use std::io::Cursor;
25
26    use super::*;
27
28    #[test]
29    fn test_stream_len_bp() -> std::io::Result<()> {
30        let data = [0, 1, 2, 3, 4, 5];
31        let mut cursor = Cursor::new(&data);
32
33        assert_eq!(cursor.stream_len_bp()?, 6);
34        assert_eq!(cursor.position(), 0);
35
36        cursor.seek(SeekFrom::Start(2))?;
37        assert_eq!(cursor.stream_len_bp()?, 6);
38        assert_eq!(cursor.position(), 2);
39
40        cursor.seek(SeekFrom::End(0))?;
41        assert_eq!(cursor.stream_len_bp()?, 6);
42        assert_eq!(cursor.position(), 6);
43        Ok(())
44    }
45}