-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move SeekForward trait to seek_forward.rs
- Loading branch information
Showing
2 changed files
with
57 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// Copyright (C) 2024, Benjamin Drung <[email protected]> | ||
// SPDX-License-Identifier: ISC | ||
|
||
use std::fs::File; | ||
use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom}; | ||
use std::process::ChildStdout; | ||
|
||
const PIPE_SIZE: usize = 65536; | ||
|
||
pub trait SeekForward { | ||
/// Seek forward to an offset, in bytes, in a stream. | ||
/// | ||
/// A seek beyond the end of a stream is allowed, but behavior is defined | ||
/// by the implementation. | ||
/// | ||
/// # Errors | ||
/// | ||
/// Seeking can fail, for example because it might involve flushing a buffer. | ||
fn seek_forward(&mut self, offset: u64) -> Result<()>; | ||
} | ||
|
||
impl SeekForward for File { | ||
fn seek_forward(&mut self, offset: u64) -> Result<()> { | ||
self.seek(SeekFrom::Current(offset.try_into().unwrap()))?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
impl SeekForward for ChildStdout { | ||
fn seek_forward(&mut self, offset: u64) -> Result<()> { | ||
let mut seek_reader = self.take(offset); | ||
let mut remaining: usize = offset.try_into().unwrap(); | ||
let mut buffer = [0; PIPE_SIZE]; | ||
while remaining > 0 { | ||
let read = seek_reader.read(&mut buffer)?; | ||
remaining -= read; | ||
} | ||
Ok(()) | ||
} | ||
} | ||
|
||
impl SeekForward for &[u8] { | ||
fn seek_forward(&mut self, offset: u64) -> Result<()> { | ||
let mut seek_reader = std::io::Read::take(self, offset); | ||
let mut buffer = Vec::new(); | ||
let read = seek_reader.read_to_end(&mut buffer)?; | ||
if read < offset.try_into().unwrap() { | ||
return Err(Error::new( | ||
ErrorKind::UnexpectedEof, | ||
format!("read only {} bytes, but {} wanted", read, offset), | ||
)); | ||
} | ||
Ok(()) | ||
} | ||
} |