simple_bytes/
bytes_seek.rs

1
2use std::fmt;
3
4/// Get's returned when there is not enough data left to seek to the position.
5///
6/// The max position get's returned.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct SeekError(pub usize);
9
10impl fmt::Display for SeekError {
11	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12		fmt::Debug::fmt(self, f)
13	}
14}
15
16impl std::error::Error for SeekError {}
17
18
19/// Sets the internal position for writing or reading.
20pub trait BytesSeek {
21	/// Returns the internal position.
22	fn position(&self) -> usize;
23
24	/// Sets the internal position if possible.
25	fn try_seek(&mut self, pos: usize) -> Result<(), SeekError>;
26
27	/// Sets the internal position.
28	#[track_caller]
29	fn seek(&mut self, pos: usize) {
30		self.try_seek(pos).expect("failed to seek");
31	}
32
33	/// Advances the internal position if possible.
34	fn try_advance(&mut self, adv: usize) -> Result<(), SeekError> {
35		self.try_seek(self.position() + adv)
36	}
37
38	/// Advances the internal position.
39	/// 
40	/// ## Panic
41	/// May panic depending on the `BytesSeek::seek` implementation.
42	#[track_caller]
43	fn advance(&mut self, adv: usize) {
44		self.try_advance(adv).expect("failed to advance")
45	}
46}
47
48impl<S: BytesSeek> BytesSeek for &mut S {
49	#[inline]
50	fn position(&self) -> usize {
51		(**self).position()
52	}
53
54	#[inline]
55	fn try_seek(&mut self, pos: usize) -> Result<(), SeekError> {
56		(**self).try_seek(pos)
57	}
58}