binrw/file_ptr.rs
1//! Type definitions and helpers for handling indirection within a file.
2//!
3//! # Best practices
4//!
5//! Indirections that are not collections (e.g. a single offset to a global file
6//! header) can use `FilePtr` to immediately read the offset and then parse the
7//! pointed-to value. However, using `FilePtr` inside a collection is
8//! inefficient because it seeks to and reads each pointed-to value immediately
9//! after the offset is read. In these cases, it is faster to read the offset
10//! table into a collection (e.g. `Vec<u32>`) and then either pass it to
11//! [`parse_from_iter`] or write a function that is called to lazily load values
12//! as needed.
13//!
14//! ## Using `parse_from_iter` to read an offset table
15//!
16//! ### With relative offsets
17//!
18//! In this example, the offsets in the offset table start counting from the
19//! beginning of the values section, and are in a random order.
20//!
21//! Since the values section exists immediately after the offset table, no
22//! seeking is required before reading the values.
23//!
24//! Since the offsets are in a random order, the position of the stream must be
25//! returned to a known state using `restore_position` on the values field.
26//! Then, `seek_before` is used on the next field to skip past the values data
27//! and continue reading the rest of the object.
28//!
29//! ```
30//! # use binrw::{args, BinRead, BinReaderExt, io::{Cursor, SeekFrom}};
31//! use binrw::file_ptr::parse_from_iter;
32//!
33//! #[derive(BinRead)]
34//! #[br(big)]
35//! struct Object {
36//! count: u16,
37//! #[br(args { count: count.into() })]
38//! offsets: Vec<u16>,
39//! #[br(parse_with = parse_from_iter(offsets.iter().copied()), restore_position)]
40//! values: Vec<u8>,
41//! #[br(seek_before(SeekFrom::Current(count.into())))]
42//! extra: u16,
43//! }
44//!
45//! # let mut x = Cursor::new(b"\0\x02\0\x01\0\0\x03\x04\xff\xff");
46//! # let x = Object::read(&mut x).unwrap();
47//! # assert_eq!(x.values, &[4, 3]);
48//! # assert_eq!(x.extra, 0xffff);
49//! ```
50//!
51//! ### With absolute offsets
52//!
53//! In this example, the offsets in the offset table start from the beginning of
54//! the file, and are in sequential order.
55//!
56//! Since the offsets start from the beginning of the file, it is necessary to
57//! use `seek_before` to reposition the stream to the beginning of the file
58//! before reading the values.
59//!
60//! Since the offsets are in order, no seeking is required after the values are
61//! read, since the stream will already be pointed at the end of the values
62//! section.
63//!
64//! ```
65//! # use binrw::{args, BinRead, BinReaderExt, io::{Cursor, SeekFrom}};
66//! use binrw::file_ptr::parse_from_iter;
67//!
68//! #[derive(BinRead)]
69//! #[br(big)]
70//! struct Object {
71//! count: u16,
72//! #[br(args { count: count.into() })]
73//! offsets: Vec<u16>,
74//! #[br(
75//! parse_with = parse_from_iter(offsets.iter().copied()),
76//! seek_before(SeekFrom::Start(0))
77//! )]
78//! values: Vec<u8>,
79//! extra: u16,
80//! }
81//!
82//! # let mut x = Cursor::new(b"\0\x02\0\x06\0\x07\x04\x03\xff\xff");
83//! # let x = Object::read(&mut x).unwrap();
84//! # assert_eq!(x.values, &[4, 3]);
85//! # assert_eq!(x.extra, 0xffff);
86//! ```
87//!
88//! ## Using a function to lazily load values
89//!
90//! In this example, only the offset table is parsed. Values pointed to by the
91//! offset table are loaded on demand by calling `Object::get` as needed at
92//! runtime.
93//!
94//! ```
95//! # use binrw::{args, BinRead, BinResult, BinReaderExt, helpers::until_eof, io::{Cursor, Read, Seek, SeekFrom}};
96//!
97//! #[derive(BinRead)]
98//! # #[derive(Debug, Eq, PartialEq)]
99//! #[br(big)]
100//! struct Item(u8);
101//!
102//! #[derive(BinRead)]
103//! #[br(big, stream = s)]
104//! struct Object {
105//! count: u16,
106//! #[br(args { count: count.into() })]
107//! offsets: Vec<u16>,
108//! #[br(try_calc = s.stream_position())]
109//! data_offset: u64,
110//! }
111//!
112//! impl Object {
113//! pub fn get<R: Read + Seek>(&self, source: &mut R, index: usize) -> Option<BinResult<Item>> {
114//! self.offsets.get(index).map(|offset| {
115//! let offset = self.data_offset + u64::from(*offset);
116//! source.seek(SeekFrom::Start(offset))?;
117//! Item::read(source)
118//! })
119//! }
120//! }
121//!
122//! # let mut s = Cursor::new(b"\0\x02\0\x01\0\0\x03\x04");
123//! # let x = Object::read(&mut s).unwrap();
124//! # assert!(matches!(x.get(&mut s, 0), Some(Ok(Item(4)))));
125//! # assert!(matches!(x.get(&mut s, 1), Some(Ok(Item(3)))));
126//! # assert!(matches!(x.get(&mut s, 2), None));
127//! ```
128
129use crate::NamedArgs;
130use crate::{
131 io::{Read, Seek, SeekFrom},
132 BinRead, BinResult, Endian,
133};
134use core::num::{
135 NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU128, NonZeroU16,
136 NonZeroU32, NonZeroU64, NonZeroU8,
137};
138use core::ops::{Deref, DerefMut};
139
140/// A type alias for [`FilePtr`] with 8-bit offsets.
141pub type FilePtr8<T> = FilePtr<u8, T>;
142/// A type alias for [`FilePtr`] with 16-bit offsets.
143pub type FilePtr16<T> = FilePtr<u16, T>;
144/// A type alias for [`FilePtr`] with 32-bit offsets.
145pub type FilePtr32<T> = FilePtr<u32, T>;
146/// A type alias for [`FilePtr`] with 64-bit offsets.
147pub type FilePtr64<T> = FilePtr<u64, T>;
148/// A type alias for [`FilePtr`] with 128-bit offsets.
149pub type FilePtr128<T> = FilePtr<u128, T>;
150
151/// A type alias for [`FilePtr`] with non-zero 8-bit offsets.
152pub type NonZeroFilePtr8<T> = FilePtr<NonZeroU8, T>;
153/// A type alias for [`FilePtr`] with non-zero 16-bit offsets.
154pub type NonZeroFilePtr16<T> = FilePtr<NonZeroU16, T>;
155/// A type alias for [`FilePtr`] with non-zero 32-bit offsets.
156pub type NonZeroFilePtr32<T> = FilePtr<NonZeroU32, T>;
157/// A type alias for [`FilePtr`] with non-zero 64-bit offsets.
158pub type NonZeroFilePtr64<T> = FilePtr<NonZeroU64, T>;
159/// A type alias for [`FilePtr`] with non-zero 128-bit offsets.
160pub type NonZeroFilePtr128<T> = FilePtr<NonZeroU128, T>;
161
162/// A wrapper type which represents a layer of indirection within a file.
163///
164/// The pointer type `Ptr` is an offset to a value within the data stream, and
165/// the value type `T` is the value at that offset. [Dereferencing] a `FilePtr`
166/// yields the pointed-to value. When deriving `BinRead`, the
167/// [offset](crate::docs::attribute#offset) directive can be used to adjust the
168/// offset before the pointed-to value is read.
169///
170/// `FilePtr` is not efficient when reading offset tables; see the
171/// [module documentation](binrw::file_ptr) for more information.
172///
173/// [Dereferencing]: core::ops::Deref
174///
175/// # Examples
176///
177/// ```
178/// # use binrw::{prelude::*, io::Cursor, FilePtr};
179/// #
180/// #[derive(BinRead)]
181/// struct Test {
182/// indirect_value: FilePtr<u32, u8>
183/// }
184///
185/// let test: Test = Cursor::new(b"\0\0\0\x08\0\0\0\0\xff").read_be().unwrap();
186/// assert_eq!(test.indirect_value.ptr, 8);
187/// assert_eq!(*test.indirect_value, 0xFF);
188/// ```
189///
190/// Example data mapped out:
191///
192/// ```hex
193/// [pointer] [value]
194/// 00000000: 0000 0008 0000 0000 ff ............
195/// ```
196#[derive(Debug, Eq)]
197pub struct FilePtr<Ptr: IntoSeekFrom, T> {
198 /// The raw offset to the value.
199 pub ptr: Ptr,
200
201 /// The pointed-to value.
202 pub value: T,
203}
204
205impl<Ptr, Value> BinRead for FilePtr<Ptr, Value>
206where
207 Ptr: for<'a> BinRead<Args<'a> = ()> + IntoSeekFrom,
208 Value: BinRead,
209{
210 type Args<'a> = FilePtrArgs<Value::Args<'a>>;
211
212 fn read_options<R: Read + Seek>(
213 reader: &mut R,
214 endian: Endian,
215 args: Self::Args<'_>,
216 ) -> BinResult<Self> {
217 let ptr = Ptr::read_options(reader, endian, ())?;
218 let value = Self::read_value(ptr, Value::read_options, reader, endian, args)?;
219 Ok(FilePtr { ptr, value })
220 }
221}
222
223impl<Ptr, Value> FilePtr<Ptr, Value>
224where
225 Ptr: IntoSeekFrom,
226{
227 /// Reads an offset, then seeks to and parses the pointed-to value using the
228 /// [`BinRead`] implementation for `Value`. Returns the pointed-to value.
229 ///
230 /// # Errors
231 ///
232 /// If reading fails, an [`Error`](crate::Error) variant will be returned.
233 #[binrw::parser(reader, endian)]
234 pub fn parse<Args>(args: FilePtrArgs<Args>, _: ...) -> BinResult<Value>
235 where
236 Ptr: for<'a> BinRead<Args<'a> = ()> + IntoSeekFrom,
237 Value: for<'a> BinRead<Args<'a> = Args>,
238 {
239 Self::read_options(reader, endian, args).map(Self::into_inner)
240 }
241
242 /// Creates a parser that reads an offset, then seeks to and parses the
243 /// pointed-to value using the given `parser` function. Returns the
244 /// pointed-to value.
245 ///
246 /// # Errors
247 ///
248 /// If reading fails, an [`Error`](crate::Error) variant will be returned.
249 pub fn parse_with<R, F, Args>(
250 parser: F,
251 ) -> impl Fn(&mut R, Endian, FilePtrArgs<Args>) -> BinResult<Value>
252 where
253 R: Read + Seek,
254 F: Fn(&mut R, Endian, Args) -> BinResult<Value>,
255 Ptr: for<'a> BinRead<Args<'a> = ()> + IntoSeekFrom,
256 {
257 let parser = Self::with(parser);
258 move |reader, endian, args| parser(reader, endian, args).map(Self::into_inner)
259 }
260
261 /// Creates a parser that reads an offset, then seeks to and parses the
262 /// pointed-to value using the given `parser` function. Returns a
263 /// [`FilePtr`] containing the offset and value.
264 ///
265 /// # Errors
266 ///
267 /// If reading fails, an [`Error`](crate::Error) variant will be returned.
268 pub fn with<R, F, Args>(
269 parser: F,
270 ) -> impl Fn(&mut R, Endian, FilePtrArgs<Args>) -> BinResult<Self>
271 where
272 R: Read + Seek,
273 F: Fn(&mut R, Endian, Args) -> BinResult<Value>,
274 Ptr: for<'a> BinRead<Args<'a> = ()> + IntoSeekFrom,
275 {
276 move |reader, endian, args| {
277 let ptr = Ptr::read_options(reader, endian, ())?;
278 let value = Self::read_value(ptr, &parser, reader, endian, args)?;
279 Ok(Self { ptr, value })
280 }
281 }
282
283 /// Consumes this object, returning the pointed-to value.
284 pub fn into_inner(self) -> Value {
285 self.value
286 }
287
288 fn read_value<R, Parser, Args>(
289 ptr: Ptr,
290 parser: Parser,
291 reader: &mut R,
292 endian: Endian,
293 args: FilePtrArgs<Args>,
294 ) -> BinResult<Value>
295 where
296 R: Read + Seek,
297 Parser: FnOnce(&mut R, Endian, Args) -> BinResult<Value>,
298 {
299 let relative_to = args.offset;
300 let before = reader.stream_position()?;
301 reader.seek(SeekFrom::Start(relative_to))?;
302 reader.seek(ptr.into_seek_from())?;
303 let value = parser(reader, endian, args.inner);
304 reader.seek(SeekFrom::Start(before))?;
305 value
306 }
307}
308
309impl<Ptr, Value> Deref for FilePtr<Ptr, Value>
310where
311 Ptr: IntoSeekFrom,
312{
313 type Target = Value;
314
315 fn deref(&self) -> &Self::Target {
316 &self.value
317 }
318}
319
320impl<Ptr, Value> DerefMut for FilePtr<Ptr, Value>
321where
322 Ptr: IntoSeekFrom,
323{
324 fn deref_mut(&mut self) -> &mut Value {
325 &mut self.value
326 }
327}
328
329impl<Ptr, Value> PartialEq<FilePtr<Ptr, Value>> for FilePtr<Ptr, Value>
330where
331 Ptr: IntoSeekFrom,
332 Value: PartialEq,
333{
334 fn eq(&self, other: &Self) -> bool {
335 self.value == other.value
336 }
337}
338
339/// Creates a parser that reads a collection of values from an iterator of
340/// file offsets using the [`BinRead`] implementation of `Value`.
341///
342/// Offsets are treated as relative to the position of the reader when
343/// parsing begins. Use the [`seek_before`] directive to reposition the
344/// stream in this case.
345///
346/// See the [module documentation](binrw::file_ptr) for more information on how
347/// use `parse_from_iter`.
348///
349/// [`seek_before`]: crate::docs::attribute#padding-and-alignment
350///
351/// # Examples
352///
353/// ```
354/// # use binrw::{args, BinRead, BinReaderExt, io::Cursor};
355/// #[derive(BinRead)]
356/// #[br(big)]
357/// struct Header {
358/// count: u16,
359///
360/// #[br(args { count: count.into() })]
361/// offsets: Vec<u16>,
362/// }
363///
364/// #[derive(BinRead)]
365/// #[br(big)]
366/// struct Object {
367/// header: Header,
368/// #[br(parse_with = binrw::file_ptr::parse_from_iter(header.offsets.iter().copied()))]
369/// values: Vec<u8>,
370/// }
371///
372/// # let mut x = Cursor::new(b"\0\x02\0\x01\0\0\x03\x04");
373/// # let x = Object::read(&mut x).unwrap();
374/// # assert_eq!(x.values, &[4, 3]);
375/// ```
376pub fn parse_from_iter<Ptr, Value, Ret, Args, It, Reader>(
377 it: It,
378) -> impl FnOnce(&mut Reader, Endian, Args) -> BinResult<Ret>
379where
380 Ptr: IntoSeekFrom,
381 Value: for<'a> BinRead<Args<'a> = Args>,
382 Ret: FromIterator<Value>,
383 Args: Clone,
384 It: IntoIterator<Item = Ptr>,
385 Reader: Read + Seek,
386{
387 parse_from_iter_with(it, Value::read_options)
388}
389
390/// Creates a parser that reads a collection of values from an iterator of
391/// file offsets using the given `parser` function.
392///
393/// Offsets are treated as relative to the position of the reader when
394/// parsing begins. Use the [`seek_before`] directive to reposition the
395/// stream in this case.
396///
397/// See the [module documentation](binrw::file_ptr) for more information on how
398/// to use `parse_from_iter_with`.
399///
400/// [`seek_before`]: crate::docs::attribute#padding-and-alignment
401///
402/// # Examples
403///
404/// ```
405/// # use binrw::{args, BinRead, BinReaderExt, io::Cursor};
406/// #[derive(BinRead)]
407/// #[br(big)]
408/// struct Header {
409/// count: u16,
410///
411/// #[br(args { count: count.into() })]
412/// offsets: Vec<u16>,
413/// }
414///
415/// # #[derive(Debug, Eq, PartialEq)]
416/// struct Item(u8);
417///
418/// #[derive(BinRead)]
419/// #[br(big)]
420/// struct Object {
421/// header: Header,
422/// #[br(parse_with = binrw::file_ptr::parse_from_iter_with(header.offsets.iter().copied(), |reader, endian, args| {
423/// u8::read_options(reader, endian, args).map(Item)
424/// }))]
425/// values: Vec<Item>,
426/// }
427///
428/// # let mut x = Cursor::new(b"\0\x02\0\x01\0\0\x03\x04");
429/// # let x = Object::read(&mut x).unwrap();
430/// # assert_eq!(x.values, &[Item(4), Item(3)]);
431/// ```
432pub fn parse_from_iter_with<Ptr, Value, Ret, Args, It, F, Reader>(
433 it: It,
434 parser: F,
435) -> impl FnOnce(&mut Reader, Endian, Args) -> BinResult<Ret>
436where
437 Ptr: IntoSeekFrom,
438 Ret: FromIterator<Value>,
439 Args: Clone,
440 It: IntoIterator<Item = Ptr>,
441 F: Fn(&mut Reader, Endian, Args) -> BinResult<Value>,
442 Reader: Read + Seek,
443{
444 move |reader, endian, args| {
445 let base_pos = reader.stream_position()?;
446 it.into_iter()
447 .map(move |ptr| {
448 // Avoid unnecessary seeks:
449 // 1. Unnecessary seeking backwards to the base position
450 // will cause forward-only readers to fail always even if
451 // the offsets are ordered;
452 // 2. Seeks that change the position when it does not need
453 // to change may unnecessarily flush a buffered reader
454 // cache.
455 match ptr.into_seek_from() {
456 seek @ SeekFrom::Current(offset) => {
457 if let Some(new_pos) = base_pos.checked_add_signed(offset) {
458 if new_pos != reader.stream_position()? {
459 reader.seek(SeekFrom::Start(new_pos))?;
460 }
461 } else {
462 reader.seek(seek)?;
463 }
464 }
465 seek => {
466 reader.seek(seek)?;
467 }
468 }
469
470 parser(reader, endian, args.clone())
471 })
472 .collect()
473 }
474}
475
476/// A trait to convert from an integer into
477/// [`SeekFrom::Current`](crate::io::SeekFrom::Current).
478pub trait IntoSeekFrom: Copy {
479 /// Converts the value.
480 fn into_seek_from(self) -> SeekFrom;
481}
482
483macro_rules! impl_into_seek_from {
484 ($($t:ty),*) => {
485 $(
486 impl IntoSeekFrom for $t {
487 fn into_seek_from(self) -> SeekFrom {
488 SeekFrom::Current(TryInto::try_into(self).unwrap())
489 }
490 }
491 )*
492 };
493}
494
495impl_into_seek_from!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);
496
497macro_rules! impl_into_seek_from_for_non_zero {
498 ($($t:ty),*) => {
499 $(
500 impl IntoSeekFrom for $t {
501 fn into_seek_from(self) -> SeekFrom {
502 self.get().into_seek_from()
503 }
504 }
505 )*
506 };
507}
508
509impl_into_seek_from_for_non_zero!(
510 NonZeroI128,
511 NonZeroI16,
512 NonZeroI32,
513 NonZeroI64,
514 NonZeroI8,
515 NonZeroU128,
516 NonZeroU16,
517 NonZeroU32,
518 NonZeroU64,
519 NonZeroU8
520);
521
522/// Named arguments for the [`BinRead::read_options()`] implementation of [`FilePtr`].
523///
524/// The `inner` field can be omitted completely if the inner type doesn’t
525/// require arguments, in which case a default value will be used.
526#[derive(Clone, Default, NamedArgs)]
527pub struct FilePtrArgs<Inner> {
528 /// An absolute offset added to the [`FilePtr::ptr`](crate::FilePtr::ptr)
529 /// offset before reading the pointed-to value.
530 #[named_args(default = 0)]
531 pub offset: u64,
532
533 /// The [arguments](crate::BinRead::Args) for the inner type.
534 #[named_args(try_optional)]
535 pub inner: Inner,
536}