Skip to main content

rpfm_lib/binary/
reader.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Module with the [`ReadBytes`] trait, to read bytes to known types.
12
13use byteorder::{LittleEndian, ReadBytesExt};
14use encoding_rs::{ISO_8859_15, UTF_16LE};
15use itertools::Itertools;
16use nalgebra::{Vector2, Vector4};
17
18use std::io::{Read, Seek, SeekFrom};
19
20use crate::error::{Result, RLibError};
21
22//---------------------------------------------------------------------------//
23//                            Trait Definition
24//---------------------------------------------------------------------------//
25
26/// This trait allow us to easily read all kind of data from a source that implements [`Read`] + [`Seek`].
27pub trait ReadBytes: Read + Seek {
28
29    /// This function returns the length of the data we're reading.
30    ///
31    /// Extracted from the nightly std.
32    ///
33    /// ```rust
34    /// use std::io::Cursor;
35    ///
36    /// use rpfm_lib::binary::ReadBytes;
37    ///
38    /// let data = vec![1, 2, 3, 4];
39    /// let mut cursor = Cursor::new(data);
40    /// let len = cursor.len().unwrap();
41    /// assert_eq!(len, 4);
42    /// ```
43    fn len(&mut self) -> Result<u64> {
44        let old_pos = self.stream_position()?;
45        let len = self.seek(SeekFrom::End(0))?;
46        // Avoid seeking a third time when we were already at the end of the
47        // stream. The branch is usually way cheaper than a seek operation.
48        if old_pos != len {
49            self.seek(SeekFrom::Start(old_pos))?;
50        }
51        Ok(len)
52    }
53
54    /// This function returns if the data is empty.
55    ///
56    /// It's slightly faster than checking for len == 0.
57    ///
58    /// ```rust
59    /// use std::io::Cursor;
60    ///
61    /// use rpfm_lib::binary::ReadBytes;
62    ///
63    /// let data = vec![];
64    /// let mut cursor = Cursor::new(data);
65    /// assert!(ReadBytes::is_empty(&mut cursor).unwrap());
66    /// ```
67    fn is_empty(&mut self) -> Result<bool> {
68        self.len().map(|len| len == 0)
69    }
70
71    /// This function returns the amount of bytes specified in the `size` argument as a [`Vec<u8>`].
72    ///
73    /// If `rewind` is true, the cursor will be reset to its original position once the data is returned.
74    ///
75    /// ```rust
76    /// use std::io::Cursor;
77    ///
78    /// use rpfm_lib::binary::ReadBytes;
79    ///
80    /// let data = vec![1, 2, 3, 4];
81    /// let mut cursor = Cursor::new(data.to_vec());
82    /// let data_read = cursor.read_slice(4, false).unwrap();
83    /// assert_eq!(data, data_read);
84    ///
85    /// # assert_eq!(ReadBytes::read_slice(&mut Cursor::new([1, 2, 3, 4]), 4, false).unwrap(), vec![1, 2, 3, 4]);
86    /// # assert_eq!(ReadBytes::read_slice(&mut Cursor::new(vec![0u8; 0]), 0, false).unwrap(), vec![0u8; 0]);
87    /// # assert_eq!(ReadBytes::read_slice(&mut Cursor::new([]), 4, false).is_err(), true);
88    /// ```
89    fn read_slice(&mut self, size: usize, rewind: bool) -> Result<Vec<u8>> {
90        let mut data = vec![0; size];
91
92        // If len is 0, just return.
93        if size == 0 {
94            return Ok(data)
95        }
96
97        self.read_exact(&mut data)?;
98
99        if rewind {
100            self.seek(SeekFrom::Current(-(size as i64)))?;
101        }
102
103        Ok(data)
104    }
105
106    /// This function tries to read a bool value from `self`.
107    ///
108    /// This is simple: 0 is false, 1 is true. Anything else is an error.
109    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
110    ///
111    /// ```rust
112    /// use std::io::Cursor;
113    ///
114    /// use rpfm_lib::binary::ReadBytes;
115    ///
116    /// let data = vec![0, 1, 2];
117    /// let mut cursor = Cursor::new(data);
118    ///
119    /// let first = cursor.read_bool();
120    /// let second = cursor.read_bool();
121    /// let third = cursor.read_bool();
122    ///
123    /// assert_eq!(first.unwrap(), false);
124    /// assert_eq!(second.unwrap(), true);
125    /// assert!(third.is_err());
126    /// ```
127    fn read_bool(&mut self) -> Result<bool> {
128        let value = self.read_u8()?;
129        match value {
130            0 => Ok(false),
131            1 => Ok(true),
132            _ => Err(RLibError::DecodingBoolError(value)),
133        }
134    }
135
136    /// This function tries to read an unsigned byte value from `self`.
137    ///
138    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
139    ///
140    /// ```rust
141    /// use std::io::Cursor;
142    ///
143    /// use rpfm_lib::binary::ReadBytes;
144    ///
145    /// let data = vec![10];
146    /// let mut cursor = Cursor::new(data);
147    /// let data = cursor.read_u8().unwrap();
148    ///
149    /// assert_eq!(data, 10);
150    /// assert_eq!(cursor.read_u8().is_err(), true);
151    /// ```
152    fn read_u8(&mut self) -> Result<u8> {
153        ReadBytesExt::read_u8(self).map_err(From::from)
154    }
155
156    /// This function tries to read an u16 value from `self`.
157    ///
158    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
159    ///
160    /// ```rust
161    /// use std::io::Cursor;
162    ///
163    /// use rpfm_lib::binary::ReadBytes;
164    ///
165    /// let data = vec![10, 0, 10];
166    /// let mut cursor = Cursor::new(data);
167    /// let data = cursor.read_u16().unwrap();
168    ///
169    /// assert_eq!(data, 10);
170    /// assert_eq!(cursor.read_u16().is_err(), true);
171    /// ```
172    fn read_u16(&mut self) -> Result<u16> {
173        ReadBytesExt::read_u16::<LittleEndian>(self).map_err(From::from)
174    }
175
176    /// This function tries to read an u24 value from `self`.
177    ///
178    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
179    ///
180    /// ```rust
181    /// use std::io::Cursor;
182    ///
183    /// use rpfm_lib::binary::ReadBytes;
184    ///
185    /// let data = vec![152, 150, 129, 152, 150];
186    /// let mut cursor = Cursor::new(data);
187    /// let data = cursor.read_u24().unwrap();
188    ///
189    /// assert_eq!(data, 84_926_96);
190    /// assert_eq!(cursor.read_u24().is_err(), true);
191    /// ```
192    fn read_u24(&mut self) -> Result<u32> {
193        ReadBytesExt::read_u24::<LittleEndian>(self).map_err(From::from)
194    }
195
196    /// This function tries to read an u32 value from `self`.
197    ///
198    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
199    ///
200    /// ```rust
201    /// use std::io::Cursor;
202    ///
203    /// use rpfm_lib::binary::ReadBytes;
204    ///
205    /// let data = vec![10, 0, 0, 0, 10, 0, 0];
206    /// let mut cursor = Cursor::new(data);
207    /// let data = cursor.read_u32().unwrap();
208    ///
209    /// assert_eq!(data, 10);
210    /// assert_eq!(cursor.read_u32().is_err(), true);
211    /// ```
212    fn read_u32(&mut self) -> Result<u32> {
213        ReadBytesExt::read_u32::<LittleEndian>(self).map_err(From::from)
214    }
215
216    /// This function tries to read an u64 value from `self`.
217    ///
218    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
219    ///
220    /// ```rust
221    /// use std::io::Cursor;
222    ///
223    /// use rpfm_lib::binary::ReadBytes;
224    ///
225    /// let data = vec![10, 0, 0, 0, 0, 0, 0, 0, 10, 0];
226    /// let mut cursor = Cursor::new(data);
227    /// let data = cursor.read_u64().unwrap();
228    ///
229    /// assert_eq!(data, 10);
230    /// assert_eq!(cursor.read_u64().is_err(), true);
231    /// ```
232    fn read_u64(&mut self) -> Result<u64> {
233        ReadBytesExt::read_u64::<LittleEndian>(self).map_err(From::from)
234    }
235
236    /// This function tries to read CA's own take (or I greatly misunderstood this) on ULEB_128 values from `self`.
237    ///
238    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
239    ///
240    /// ```rust
241    /// use std::io::Cursor;
242    ///
243    /// use rpfm_lib::binary::ReadBytes;
244    ///
245    /// let data = vec![0x80, 10];
246    /// let mut cursor = Cursor::new(data);
247    /// let data = cursor.read_cauleb128().unwrap();
248    ///
249    /// assert_eq!(data, 10);
250    /// assert_eq!(cursor.read_cauleb128().is_err(), true);
251    /// ```
252    fn read_cauleb128(&mut self) -> Result<u32> {
253        let mut value: u32 = 0;
254        let mut byte = self.read_u8()?;
255
256        while(byte & 0x80) != 0 {
257            value = (value << 7) | (byte & 0x7f) as u32;
258
259            // Check the new byte is even valid before continuing.
260            byte = self.read_u8()?;
261        }
262
263        value = (value << 7) | (byte & 0x7f) as u32;
264        Ok(value)
265    }
266
267    /// This function tries to read a signed byte value from `self`.
268    ///
269    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
270    ///
271    /// ```rust
272    /// use std::io::Cursor;
273    ///
274    /// use rpfm_lib::binary::ReadBytes;
275    ///
276    /// let data = vec![254];
277    /// let mut cursor = Cursor::new(data);
278    /// let data = cursor.read_i8().unwrap();
279    ///
280    /// assert_eq!(data, -2);
281    /// assert_eq!(cursor.read_i8().is_err(), true);
282    /// ```
283    fn read_i8(&mut self) -> Result<i8> {
284        ReadBytesExt::read_i8(self).map_err(From::from)
285    }
286
287    /// This function tries to read an i16 value from `self`.
288    ///
289    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
290    ///
291    /// ```rust
292    /// use std::io::Cursor;
293    ///
294    /// use rpfm_lib::binary::ReadBytes;
295    ///
296    /// let data = vec![254, 254, 10];
297    /// let mut cursor = Cursor::new(data);
298    /// let data = cursor.read_i16().unwrap();
299    ///
300    /// assert_eq!(data, -258);
301    /// assert_eq!(cursor.read_i16().is_err(), true);
302    /// ```
303    fn read_i16(&mut self) -> Result<i16> {
304        ReadBytesExt::read_i16::<LittleEndian>(self).map_err(From::from)
305    }
306
307    /// This function tries to read an i24 value from `self`.
308    ///
309    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
310    ///
311    /// ```rust
312    /// use std::io::Cursor;
313    ///
314    /// use rpfm_lib::binary::ReadBytes;
315    ///
316    /// let data = vec![152, 150, 129, 152, 150];
317    /// let mut cursor = Cursor::new(data);
318    /// let data = cursor.read_i24().unwrap();
319    ///
320    /// assert_eq!(data, -8_284_520);
321    /// assert_eq!(cursor.read_i24().is_err(), true);
322    /// ```
323    fn read_i24(&mut self) -> Result<i32> {
324        ReadBytesExt::read_i24::<LittleEndian>(self).map_err(From::from)
325    }
326
327    /// This function tries to read an i32 value from `self`.
328    ///
329    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
330    ///
331    /// ```rust
332    /// use std::io::Cursor;
333    ///
334    /// use rpfm_lib::binary::ReadBytes;
335    ///
336    /// let data = vec![10, 0, 0, 0, 10, 0, 0];
337    /// let mut cursor = Cursor::new(data);
338    /// let data = cursor.read_i32().unwrap();
339    ///
340    /// assert_eq!(data, 10);
341    /// assert_eq!(cursor.read_i32().is_err(), true);
342    /// ```
343    fn read_i32(&mut self) -> Result<i32> {
344        ReadBytesExt::read_i32::<LittleEndian>(self).map_err(From::from)
345    }
346
347    /// This function tries to read an i64 value from `self`.
348    ///
349    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
350    ///
351    /// ```rust
352    /// use std::io::Cursor;
353    ///
354    /// use rpfm_lib::binary::ReadBytes;
355    ///
356    /// let data = vec![10, 0, 0, 0, 0, 0, 0, 0, 10, 0];
357    /// let mut cursor = Cursor::new(data);
358    /// let data = cursor.read_i64().unwrap();
359    ///
360    /// assert_eq!(data, 10);
361    /// assert_eq!(cursor.read_i64().is_err(), true);
362    /// ```
363    fn read_i64(&mut self) -> Result<i64> {
364        ReadBytesExt::read_i64::<LittleEndian>(self).map_err(From::from)
365    }
366
367    /// This function tries to read an optional i16 value from `self`.
368    ///
369    /// The value is preceeded by a bool. If the bool is true, we expect a value after it.
370    /// If its false, we expect a sentinel value (0) after it.
371    ///
372    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
373    ///
374    /// ```rust
375    /// use std::io::Cursor;
376    ///
377    /// use rpfm_lib::binary::ReadBytes;
378    ///
379    /// let data = vec![1, 254, 254, 2];
380    /// let mut cursor = Cursor::new(data);
381    /// let data = cursor.read_optional_i16().unwrap();
382    ///
383    /// assert_eq!(data, -258);
384    /// assert_eq!(cursor.read_optional_i16().is_err(), true);
385    ///
386    /// # assert_eq!(ReadBytes::read_optional_i16(&mut Cursor::new([1, 10])).is_err(), true);
387    /// ```
388    fn read_optional_i16(&mut self) -> Result<i16> {
389        let _ = self.read_bool()?;
390        self.read_i16()
391    }
392
393    /// This function tries to read an optional i32 value from `self`.
394    ///
395    /// The value is preceeded by a bool. If the bool is true, we expect a value after it.
396    /// If its false, we expect a sentinel value (0) after it.
397    ///
398    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
399    ///
400    /// ```rust
401    /// use std::io::Cursor;
402    ///
403    /// use rpfm_lib::binary::ReadBytes;
404    ///
405    /// let data = vec![1, 10, 0, 0, 0, 2];
406    /// let mut cursor = Cursor::new(data);
407    /// let data = cursor.read_optional_i32().unwrap();
408    ///
409    /// assert_eq!(data, 10);
410    /// assert_eq!(cursor.read_optional_i32().is_err(), true);
411    ///
412    /// # assert_eq!(ReadBytes::read_optional_i32(&mut Cursor::new([1, 10])).is_err(), true);
413    /// ```
414    fn read_optional_i32(&mut self) -> Result<i32> {
415        let _ = self.read_bool()?;
416        self.read_i32()
417    }
418
419    /// This function tries to read an optional i64 value from `self`.
420    ///
421    /// The value is preceeded by a bool. If the bool is true, we expect a value after it.
422    /// If its false, we expect a sentinel value (0) after it.
423    ///
424    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
425    ///
426    /// ```rust
427    /// use std::io::Cursor;
428    ///
429    /// use rpfm_lib::binary::ReadBytes;
430    ///
431    /// let data = vec![1, 10, 0, 0, 0, 0, 0, 0, 0, 2];
432    /// let mut cursor = Cursor::new(data);
433    /// let data = cursor.read_optional_i64().unwrap();
434    ///
435    /// assert_eq!(data, 10);
436    /// assert_eq!(cursor.read_optional_i64().is_err(), true);
437    ///
438    /// # assert_eq!(ReadBytes::read_optional_i64(&mut Cursor::new([1, 10])).is_err(), true);
439    /// ```
440    fn read_optional_i64(&mut self) -> Result<i64> {
441        let _ = self.read_bool()?;
442        self.read_i64()
443    }
444
445    /// This function tries to read an f16 value from `self`.
446    ///
447    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
448    ///
449    /// ```rust
450    /// use std::io::Cursor;
451    ///
452    /// use rpfm_lib::binary::ReadBytes;
453    ///
454    /// let data = vec![32, 65];
455    /// let mut cursor = Cursor::new(data);
456    /// let data = cursor.read_f16().unwrap();
457    ///
458    /// assert_eq!(data, half::f16::from_f32(2.5625));
459    /// assert_eq!(cursor.read_f16().is_err(), true);
460    /// ```
461    fn read_f16(&mut self) -> Result<half::f16> {
462        Ok(half::f16::from_bits(self.read_u16()?))
463    }
464
465    /// This function tries to read an f32 value from `self`.
466    ///
467    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
468    ///
469    /// ```rust
470    /// use std::io::Cursor;
471    ///
472    /// use rpfm_lib::binary::ReadBytes;
473    ///
474    /// let data = vec![0, 0, 32, 65];
475    /// let mut cursor = Cursor::new(data);
476    /// let data = cursor.read_f32().unwrap();
477    ///
478    /// assert_eq!(data, 10.0);
479    /// assert_eq!(cursor.read_f32().is_err(), true);
480    /// ```
481    fn read_f32(&mut self) -> Result<f32> {
482        ReadBytesExt::read_f32::<LittleEndian>(self).map_err(From::from)
483    }
484
485    /// This function tries to read an f32 value encoded in a single byte from `self`.
486    ///
487    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
488    ///
489    /// ```rust
490    /// use std::io::Cursor;
491    ///
492    /// use rpfm_lib::binary::ReadBytes;
493    ///
494    /// let data = vec![32];
495    /// let mut cursor = Cursor::new(data);
496    /// let data = cursor.read_f32_normal_from_u8().unwrap();
497    ///
498    /// assert_eq!(data, -0.7490196);
499    /// assert_eq!(cursor.read_f32_normal_from_u8().is_err(), true);
500    /// ```
501    fn read_f32_normal_from_u8(&mut self) -> Result<f32> {
502        Ok(self.read_u8()? as f32 / 255.0 * 2.0 - 1.0)
503    }
504
505    /// This function tries to read an f64 value from `self`.
506    ///
507    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
508    ///
509    /// ```rust
510    /// use std::io::Cursor;
511    ///
512    /// use rpfm_lib::binary::ReadBytes;
513    ///
514    /// let data = vec![0, 0, 0, 0, 0, 0, 36, 64];
515    /// let mut cursor = Cursor::new(data);
516    /// let data = cursor.read_f64().unwrap();
517    ///
518    /// assert_eq!(data, 10.0);
519    /// assert_eq!(cursor.read_f64().is_err(), true);
520    /// ```
521    fn read_f64(&mut self) -> Result<f64> {
522        ReadBytesExt::read_f64::<LittleEndian>(self).map_err(From::from)
523    }
524
525    /// This function tries to read an UTF-8 String value of the provided `size` from `self`.
526    ///
527    /// It may fail if there are not enough bytes to read the value, the value contains invalid
528    /// characters for an UTF-8 String, or `self` cannot be read.
529    ///
530    /// ```rust
531    /// use std::io::Cursor;
532    ///
533    /// use rpfm_lib::binary::ReadBytes;
534    ///
535    /// let data = vec![87, 97, 104, 97, 104, 97, 104, 97, 104, 97];
536    /// let mut cursor = Cursor::new(data);
537    /// let data = cursor.read_string_u8(10).unwrap();
538    ///
539    /// assert_eq!(data, "Wahahahaha");
540    /// assert_eq!(cursor.read_string_u8(10).is_err(), true);
541    /// ```
542    fn read_string_u8(&mut self, size: usize) -> Result<String> {
543        let mut data = vec![0; size];
544        self.read_exact(&mut data)?;
545        String::from_utf8(data).map_err(From::from)
546    }
547
548    /// This function tries to read an ISO-8859-15 String value of the provided `size` from `self`.
549    ///
550    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
551    ///
552    /// ```rust
553    /// use std::io::Cursor;
554    ///
555    /// use rpfm_lib::binary::ReadBytes;
556    ///
557    /// let data = vec![87, 97, 104, 97, 255, 104, 97, 104, 97, 104, 97];
558    /// let mut cursor = Cursor::new(data);
559    /// let data = cursor.read_string_u8_iso_8859_15(11).unwrap();
560    ///
561    /// assert_eq!(data, "Wahaÿhahaha");
562    /// assert_eq!(cursor.read_string_u8_iso_8859_15(10).is_err(), true);
563    /// ```
564    fn read_string_u8_iso_8859_15(&mut self, size: usize) -> Result<String> {
565        let mut data = vec![0; size];
566        self.read_exact(&mut data)?;
567
568        Ok(ISO_8859_15.decode(&data).0.to_string())
569    }
570
571    /// This function tries to read a 00-Padded UTF-8 String value of the provided `size` from `self`.
572    ///
573    /// Note that `size` here is the full length of the String, including the 00 bytes that act as padding.
574    ///
575    /// It may fail if there are not enough bytes to read the value, the value contains invalid
576    /// characters for an UTF-8 String, or `self` cannot be read.
577    ///
578    /// ```rust
579    /// use std::io::Cursor;
580    ///
581    /// use rpfm_lib::binary::ReadBytes;
582    ///
583    /// let data = vec![87, 97, 104, 97, 104, 97, 0, 0, 0, 0];
584    /// let mut cursor = Cursor::new(data);
585    /// let data = cursor.read_string_u8_0padded(10).unwrap();
586    ///
587    /// assert_eq!(data, "Wahaha");
588    /// assert_eq!(cursor.read_string_u8_0padded(10).is_err(), true);
589    /// ```
590    fn read_string_u8_0padded(&mut self, size: usize) -> Result<String> {
591        let mut data = vec![0; size];
592        self.read_exact(&mut data)?;
593
594        let size_no_zeros = data.iter().position(|x| *x == 0).map_or(size, |x| x);
595        String::from_utf8(data[..size_no_zeros].to_vec()).map_err(From::from)
596    }
597
598    /// This function tries to read a 00-Terminated (or NULL-Terminated) UTF-8 String value from `self`.
599    ///
600    /// It may fail if there are not enough bytes to read the value, the value contains invalid
601    /// characters for an UTF-8 String, the last value is not 00 or `self` cannot be read.
602    ///
603    /// ```rust
604    /// use std::io::Cursor;
605    ///
606    /// use rpfm_lib::binary::ReadBytes;
607    ///
608    /// let data = vec![87, 97, 104, 97, 104, 97, 104, 97, 0];
609    /// let mut cursor = Cursor::new(data);
610    /// let data = cursor.read_string_u8_0terminated().unwrap();
611    ///
612    /// assert_eq!(data, "Wahahaha");
613    /// assert_eq!(cursor.read_string_u8_0terminated().is_err(), true);
614    /// ```
615    fn read_string_u8_0terminated(&mut self) -> Result<String> {
616
617        // So, reads are expensive, so instead of reading byte by byte, we read a bunch of them
618        // and start searching with memchr. If we can't find anything, read another bunch and try again.
619        let mut buf = [0; 512];
620        let mut data = vec![];
621        let mut curr_pos = 0u64;
622        let mut end_pos = 0u64;
623        let mut found = false;
624
625        loop {
626            let read = self.read(&mut buf);
627            match read {
628                Ok(0) => break,
629                Ok(read_bytes) => {
630                    if let Some(pos) = memchr::memchr(0, &buf[..read_bytes]) {
631
632                        // If we found a 00, get the final "read" position, the final position of the 00 byte,
633                        // and mark the byte as found.
634                        end_pos = curr_pos + read_bytes as u64;
635                        curr_pos += pos as u64;
636                        data.extend_from_slice(&buf[..pos]);
637                        found = true;
638                        break;
639                    } else {
640                        curr_pos += read_bytes as u64;
641                        data.extend_from_slice(&buf);
642                    }
643                }
644
645                // If there is any error, just return it.
646                Err(error) => return Err(error)?,
647            }
648        }
649
650        // If we exited without finding the 00 byte, return an error.
651        if !found {
652            return Err(RLibError::DecodingString0TeminatedNo0Error);
653        }
654
655        // Move the cursor to the end of the value, so we can continue reading.
656        // -1 because we need to end after the 00 byte.
657        let new_pos = (end_pos - curr_pos - 1) as i64;
658        self.seek(SeekFrom::Current(-new_pos))?;
659
660        // Get a String from it. Lossy because older games have packs with broken symbols in their paths.
661        Ok(String::from_utf8_lossy(&data).to_string())
662    }
663
664    /// This function tries to read a Sized UTF-8 String value from `self`.
665    ///
666    /// In Sized Strings, the first two values of the data are the size in Characters of the string,
667    /// followed by the String itself.
668    ///
669    /// It may fail if there are not enough bytes to read the value, the value contains invalid
670    /// characters for an UTF-8 String, or `self` cannot be read.
671    ///
672    /// ```rust
673    /// use std::io::Cursor;
674    ///
675    /// use rpfm_lib::binary::ReadBytes;
676    ///
677    /// let data = vec![10, 0, 87, 97, 104, 97, 104, 97, 104, 97, 104, 97];
678    /// let mut cursor = Cursor::new(data);
679    /// let data = cursor.read_sized_string_u8().unwrap();
680    ///
681    /// assert_eq!(data, "Wahahahaha");
682    /// assert_eq!(cursor.read_sized_string_u8().is_err(), true);
683    /// ```
684    fn read_sized_string_u8(&mut self) -> Result<String> {
685        if let Ok(size) = self.read_u16() {
686            self.read_string_u8(size as usize)
687        }
688        else {
689            Err(RLibError::DecodingStringSizeError("UTF-8 String".to_owned()))
690        }
691    }
692
693    /// This function tries to read a Sized UTF-8 String value from `self`.
694    ///
695    /// In these particular Sized Strings, the first four values of the data are the size in Characters of the string,
696    /// followed by the String itself.
697    ///
698    /// It may fail if there are not enough bytes to read the value, the value contains invalid
699    /// characters for an UTF-8 String, or `self` cannot be read.
700    ///
701    /// ```rust
702    /// use std::io::Cursor;
703    ///
704    /// use rpfm_lib::binary::ReadBytes;
705    ///
706    /// let data = vec![10, 0, 0, 0, 87, 97, 104, 97, 104, 97, 104, 97, 104, 97];
707    /// let mut cursor = Cursor::new(data);
708    /// let data = cursor.read_sized_string_u8_u32().unwrap();
709    ///
710    /// assert_eq!(data, "Wahahahaha");
711    /// assert_eq!(cursor.read_sized_string_u8_u32().is_err(), true);
712    /// ```
713    fn read_sized_string_u8_u32(&mut self) -> Result<String> {
714        if let Ok(size) = self.read_u32() {
715            self.read_string_u8(size as usize)
716        }
717        else {
718            Err(RLibError::DecodingStringSizeError("UTF-8 String".to_owned()))
719        }
720    }
721
722    /// This function tries to read an Optional UTF-8 String value from `self`.
723    ///
724    /// In Optional Strings, the first byte is a boolean. If true, it's followed by a Sized String.
725    /// If false, then there is no more data after the boolean.
726    ///
727    /// It may fail if there are not enough bytes to read the value, the first value is not a boolean,
728    /// the value contains invalid, characters for an UTF-8 String, or `self` cannot be read.
729    ///
730    /// ```rust
731    /// use std::io::Cursor;
732    ///
733    /// use rpfm_lib::binary::ReadBytes;
734    ///
735    /// let data = vec![1, 10, 0, 87, 97, 104, 97, 104, 97, 104, 97, 104, 97];
736    /// let mut cursor = Cursor::new(data);
737    /// let data = cursor.read_optional_string_u8().unwrap();
738    ///
739    /// assert_eq!(data, "Wahahahaha");
740    /// assert_eq!(cursor.read_optional_string_u8().is_err(), true);
741    /// ```
742    fn read_optional_string_u8(&mut self) -> Result<String> {
743        let is = self.read_bool()
744            .map_err(|_| RLibError::DecodingOptionalStringBoolError("UTF-8 Optional String".to_owned()))?;
745
746        if is {
747            self.read_sized_string_u8()
748        } else {
749            Ok(String::new())
750        }
751    }
752
753    /// This function tries to read an UTF-16 String value of the provided `size` (in bytes) from `self`.
754    ///
755    /// It may fail if there are not enough bytes to read the value, the value contains invalid
756    /// characters for an UTF-16 String, or `self` cannot be read.
757    ///
758    /// ```rust
759    /// use std::io::Cursor;
760    ///
761    /// use rpfm_lib::binary::ReadBytes;
762    ///
763    /// let data = vec![87, 0, 97, 0, 104, 0, 97, 0, 104, 0, 97, 0];
764    /// let mut cursor = Cursor::new(data);
765    /// let data = cursor.read_string_u16(12).unwrap();
766    ///
767    /// assert_eq!(data, "Wahaha");
768    /// assert_eq!(cursor.read_string_u16(12).is_err(), true);
769    /// ```
770    fn read_string_u16(&mut self, size: usize) -> Result<String> {
771        if size % 2 == 1 {
772            return Err(RLibError::DecodeUTF16UnevenInputError(size));
773        }
774        let mut data = vec![0; size];
775        self.read_exact(&mut data)?;
776
777        Ok(UTF_16LE.decode(&data).0.to_string())
778    }
779
780    /// This function tries to read a 00-Padded UTF-16 String value of the provided `size` from `self`.
781    ///
782    /// Note that `size` here is the full length of the String in bytes, including the 00 bytes that act as padding.
783    ///
784    /// It may fail if there are not enough bytes to read the value, the value contains invalid
785    /// characters for an UTF-16 String, or `self` cannot be read.
786    ///
787    /// ```rust
788    /// use std::io::Cursor;
789    ///
790    /// use rpfm_lib::binary::ReadBytes;
791    ///
792    /// let data = vec![87, 0, 97, 0, 104, 0, 97, 0, 104, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0];
793    /// let mut cursor = Cursor::new(data);
794    /// let data = cursor.read_string_u16_0padded(20).unwrap();
795    ///
796    /// assert_eq!(data, "Wahaha");
797    /// assert_eq!(cursor.read_string_u16_0padded(20).is_err(), true);
798    /// ```
799    fn read_string_u16_0padded(&mut self, size: usize) -> Result<String> {
800        let mut data = vec![0; size];
801        self.read_exact(&mut data)?;
802
803        let size_no_zeros = (0..size.wrapping_div(2)).position(|x| data[x * 2] == 0).map_or(size.wrapping_div(2), |x| x);
804        Ok(UTF_16LE.decode(&data[..size_no_zeros * 2]).0.to_string())
805    }
806
807    /// This function tries to read a 00-Terminated (or NULL-Terminated) UTF-16 String value from `self`.
808    ///
809    /// It may fail if there are not enough bytes to read the value, the value contains invalid
810    /// characters for an UTF-16 String, the last value is not 00 or `self` cannot be read.
811    ///
812    /// ```rust
813    /// use std::io::Cursor;
814    ///
815    /// use rpfm_lib::binary::ReadBytes;
816    ///
817    /// let data = vec![87, 00, 97, 00, 104, 00, 97, 00, 104, 00, 97, 00, 104, 00, 97, 00, 00, 00];
818    /// let mut cursor = Cursor::new(data);
819    /// let data = cursor.read_string_u16_0terminated().unwrap();
820    ///
821    /// assert_eq!(data, "Wahahaha");
822    /// assert_eq!(cursor.read_string_u16_0terminated().is_err(), true);
823    /// ```
824    fn read_string_u16_0terminated(&mut self) -> Result<String> {
825
826        // So, reads are expensive, so instead of reading byte by byte, we read a bunch of them
827        // and start searching with a chunk iterator. If we can't find anything, read another bunch and try again.
828        let mut buf = [0; 512];
829        let mut data = vec![];
830        let mut curr_pos = 0u64;
831        let mut end_pos = 0u64;
832        let mut found = false;
833
834        loop {
835            let read = self.read(&mut buf);
836            match read {
837                Ok(0) => break,
838                Ok(read_bytes) => {
839
840                    if let Some(pos) = buf[..read_bytes].iter().chunks(2).into_iter().position(|chunk| {
841                        let chunk = chunk.collect::<Vec<_>>();
842                        chunk.len() == 2 && *chunk[0] == 0 && *chunk[1] == 0
843                    }) {
844
845                        // If we found a 00 00, get the final "read" position, the final position of the 00 byte,
846                        // and mark the byte as found.
847                        end_pos = curr_pos + read_bytes as u64;
848                        curr_pos += pos as u64 * 2;
849                        data.extend_from_slice(&buf[..pos * 2]);
850                        found = true;
851                        break;
852                    } else {
853                        curr_pos += read_bytes as u64;
854                        data.extend_from_slice(&buf);
855                    }
856                }
857
858                // If there is any error, just return it.
859                Err(error) => return Err(error)?,
860            }
861        }
862
863        // If we exited without finding the 00 byte, return an error.
864        if !found {
865            return Err(RLibError::DecodingString0TeminatedNo0Error);
866        }
867
868        // Move the cursor to the end of the value, so we can continue reading.
869        // -2 because we need to end after the last 00 byte.
870        let new_pos = end_pos as i64 - curr_pos as i64 - 2;
871        self.seek(SeekFrom::Current(-new_pos))?;
872
873        // Get a String from it. Lossy because older games have packs with broken symbols in their paths.
874        Ok(UTF_16LE.decode(&data).0.to_string())
875    }
876
877    /// This function tries to read a Sized UTF-16 String value from `self`.
878    ///
879    /// In Sized Strings, the first two values of the data are the size in Characters of the string,
880    /// followed by the String itself.
881    ///
882    /// It may fail if there are not enough bytes to read the value, the value contains invalid
883    /// characters for an UTF-16 String, or `self` cannot be read.
884    ///
885    /// ```rust
886    /// use std::io::Cursor;
887    ///
888    /// use rpfm_lib::binary::ReadBytes;
889    ///
890    /// let data = vec![4, 0, 87, 0, 97, 0, 104, 0, 97, 0];
891    /// let mut cursor = Cursor::new(data);
892    /// let data = cursor.read_sized_string_u16().unwrap();
893    ///
894    /// assert_eq!(data, "Waha");
895    /// assert_eq!(cursor.read_sized_string_u16().is_err(), true);
896    /// ```
897    fn read_sized_string_u16(&mut self) -> Result<String> {
898        if let Ok(size) = self.read_u16() {
899            self.read_string_u16(size.wrapping_mul(2) as usize)
900        }
901        else {
902            Err(RLibError::DecodingStringSizeError("UTF-16 String".to_owned()))
903        }
904    }
905
906    /// This function tries to read a Sized UTF-16 String value from `self`.
907    ///
908    /// In these particular Sized Strings, the first four values of the data are the size in Characters of the string,
909    /// followed by the String itself.
910    ///
911    /// It may fail if there are not enough bytes to read the value, the value contains invalid
912    /// characters for an UTF-16 String, or `self` cannot be read.
913    ///
914    /// ```rust
915    /// use std::io::Cursor;
916    ///
917    /// use rpfm_lib::binary::ReadBytes;
918    ///
919    /// let data = vec![4, 0, 0, 0, 87, 0, 97, 0, 104, 0, 97, 0];
920    /// let mut cursor = Cursor::new(data);
921    /// let data = cursor.read_sized_string_u16_u32().unwrap();
922    ///
923    /// assert_eq!(data, "Waha");
924    /// assert_eq!(cursor.read_sized_string_u16_u32().is_err(), true);
925    /// ```
926    fn read_sized_string_u16_u32(&mut self) -> Result<String> {
927        if let Ok(size) = self.read_u32() {
928            self.read_string_u16(size.wrapping_mul(2) as usize)
929        }
930        else {
931            Err(RLibError::DecodingStringSizeError("UTF-16 String".to_owned()))
932        }
933    }
934
935    /// This function tries to read an Optional UTF-16 String value from `self`.
936    ///
937    /// In Optional Strings, the first byte is a boolean. If true, it's followed by a Sized String.
938    /// If false, then there is no more data after the boolean.
939    ///
940    /// It may fail if there are not enough bytes to read the value, the first value is not a boolean,
941    /// the value contains invalid, characters for an UTF-16 String, or `self` cannot be read.
942    ///
943    /// ```rust
944    /// use std::io::Cursor;
945    ///
946    /// use rpfm_lib::binary::ReadBytes;
947    ///
948    /// let data = vec![1, 4, 0, 87, 0, 97, 0, 104, 0, 97, 0];
949    /// let mut cursor = Cursor::new(data);
950    /// let data = cursor.read_optional_string_u16().unwrap();
951    ///
952    /// assert_eq!(data, "Waha");
953    /// assert_eq!(cursor.read_optional_string_u16().is_err(), true);
954    /// ```
955    fn read_optional_string_u16(&mut self) -> Result<String> {
956        let is = self.read_bool()
957            .map_err(|_| RLibError::DecodingOptionalStringBoolError("UTF-16 Optional String".to_owned()))?;
958
959        if is {
960            self.read_sized_string_u16()
961        } else {
962            Ok(String::new())
963        }
964    }
965
966    /// This function tries to read a Hex-Encoded RGB Colour from `self`.
967    ///
968    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
969    ///
970    /// ```rust
971    /// use std::io::Cursor;
972    ///
973    /// use rpfm_lib::binary::ReadBytes;
974    ///
975    /// let data = vec![0xFF, 0x04, 0x05, 0x00];
976    /// let mut cursor = Cursor::new(data);
977    /// let data = cursor.read_string_colour_rgb().unwrap();
978    ///
979    /// assert_eq!(data, "0504FF");
980    /// assert_eq!(cursor.read_string_colour_rgb().is_err(), true);
981    /// ```
982    fn read_string_colour_rgb(&mut self) -> Result<String> {
983        let value = self.read_u32()?;
984
985        // Padding to 8 zeros so we don't lose the first one, then remove the last two zeros (alpha?).
986        // REMEMBER, FORMAT ENCODED IS BBGGRR00.
987        Ok(format!("{value:06X?}"))
988    }
989
990    /// This function tries to read a Vector of 2 u8 values from `self`.
991    ///
992    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
993    ///
994    /// ```rust
995    /// use nalgebra::Vector2;
996    /// use std::io::Cursor;
997    ///
998    /// use rpfm_lib::binary::ReadBytes;
999    ///
1000    /// let data = vec![0x0A, 0x0A];
1001    /// let mut cursor = Cursor::new(data);
1002    /// let data = cursor.read_vector_2_u8().unwrap();
1003    ///
1004    /// assert_eq!(data, Vector2::new(10, 10));
1005    /// assert_eq!(cursor.read_vector_2_u8().is_err(), true);
1006    /// ```
1007    fn read_vector_2_u8(&mut self) -> Result<Vector2<u8>> {
1008        let x = self.read_u8()?;
1009        let y = self.read_u8()?;
1010
1011        Ok(Vector2::new(x, y))
1012    }
1013
1014    /// This function tries to read a Vector of 2 f32 percentage values from `self`.
1015    ///
1016    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1017    ///
1018    /// ```rust
1019    /// use nalgebra::Vector2;
1020    /// use std::io::Cursor;
1021    ///
1022    /// use rpfm_lib::binary::ReadBytes;
1023    ///
1024    /// let data = vec![0x0A, 0x0A];
1025    /// let mut cursor = Cursor::new(data);
1026    /// let data = cursor.read_vector_2_f32_pct_from_vector_2_u8().unwrap();
1027    ///
1028    /// assert_eq!(data, Vector2::new(0.039215688, 0.039215688));
1029    /// assert_eq!(cursor.read_vector_2_f32_pct_from_vector_2_u8().is_err(), true);
1030    /// ```
1031    fn read_vector_2_f32_pct_from_vector_2_u8(&mut self) -> Result<Vector2<f32>> {
1032        let x = self.read_u8()? as f32;
1033        let y = self.read_u8()? as f32;
1034
1035        Ok(Vector2::new(x / 255.0, y / 255.0))
1036    }
1037
1038    /// This function tries to read a Vector of 2 f32 values from `self`.
1039    ///
1040    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1041    ///
1042    /// ```rust
1043    /// use nalgebra::Vector2;
1044    /// use std::io::Cursor;
1045    ///
1046    /// use rpfm_lib::binary::ReadBytes;
1047    ///
1048    /// let data = vec![0x0A, 0x0A, 0x0A, 0x0A];
1049    /// let mut cursor = Cursor::new(data);
1050    /// let data = cursor.read_vector_2_f32_from_vector_2_f16().unwrap();
1051    ///
1052    /// assert_eq!(data, Vector2::new(0.00018429756, 0.00018429756));
1053    /// assert_eq!(cursor.read_vector_2_f32_from_vector_2_f16().is_err(), true);
1054    /// ```
1055    fn read_vector_2_f32_from_vector_2_f16(&mut self) -> Result<Vector2<f32>> {
1056        let x = self.read_f16()?.to_f32();
1057        let y = self.read_f16()?.to_f32();
1058
1059        Ok(Vector2::new(x, y))
1060    }
1061
1062    /// This function tries to read a Vector of 4 u8 values from `self`.
1063    ///
1064    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1065    ///
1066    /// ```rust
1067    /// use nalgebra::Vector4;
1068    /// use std::io::Cursor;
1069    ///
1070    /// use rpfm_lib::binary::ReadBytes;
1071    ///
1072    /// let data = vec![0x0A, 0x0A, 0x0A, 0x0A];
1073    /// let mut cursor = Cursor::new(data);
1074    /// let data = cursor.read_vector_4_u8().unwrap();
1075    ///
1076    /// assert_eq!(data, Vector4::new(10, 10, 10, 10));
1077    /// assert_eq!(cursor.read_vector_4_u8().is_err(), true);
1078    /// ```
1079    fn read_vector_4_u8(&mut self) -> Result<Vector4<u8>> {
1080        let x = self.read_u8()?;
1081        let y = self.read_u8()?;
1082        let z = self.read_u8()?;
1083        let w = self.read_u8()?;
1084
1085        Ok(Vector4::new(x, y, z, w))
1086    }
1087
1088    /// This function tries to read a Vector of 4 f32 values from `self`.
1089    ///
1090    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1091    ///
1092    /// ```rust
1093    /// use nalgebra::Vector4;
1094    /// use std::io::Cursor;
1095    ///
1096    /// use rpfm_lib::binary::ReadBytes;
1097    ///
1098    /// let data = vec![
1099    ///     0x00, 0x00, 0xFF, 0x3F,
1100    ///     0x00, 0x00, 0xFF, 0x3F,
1101    ///     0x00, 0x00, 0xFF, 0x3F,
1102    ///     0x00, 0x00, 0xFF, 0x3F
1103    /// ];
1104    /// let mut cursor = Cursor::new(data);
1105    /// let data = cursor.read_vector_4_f32().unwrap();
1106    ///
1107    /// assert_eq!(data, Vector4::new(1.9921875, 1.9921875, 1.9921875, 1.9921875));
1108    /// assert_eq!(cursor.read_vector_4_f32().is_err(), true);
1109    /// ```
1110    fn read_vector_4_f32(&mut self) -> Result<Vector4<f32>> {
1111        let x = self.read_f32()?;
1112        let y = self.read_f32()?;
1113        let z = self.read_f32()?;
1114        let w = self.read_f32()?;
1115
1116        Ok(Vector4::new(x, y, z, w))
1117    }
1118
1119    /// This function tries to read a Vector of 4 f32 values from a Vector of 3 f32 values from`self`.
1120    ///
1121    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1122    ///
1123    /// ```rust
1124    /// use nalgebra::Vector4;
1125    /// use std::io::Cursor;
1126    ///
1127    /// use rpfm_lib::binary::ReadBytes;
1128    ///
1129    /// let data = vec![
1130    ///     0x00, 0x00, 0xFF, 0x3F,
1131    ///     0x00, 0x00, 0xFF, 0x3F,
1132    ///     0x00, 0x00, 0xFF, 0x3F
1133    /// ];
1134    /// let mut cursor = Cursor::new(data);
1135    /// let data = cursor.read_vector_4_f32_from_vec_3_f32().unwrap();
1136    ///
1137    /// assert_eq!(data, Vector4::new(1.9921875, 1.9921875, 1.9921875, 0.0));
1138    /// assert_eq!(cursor.read_vector_4_f32_from_vec_3_f32().is_err(), true);
1139    /// ```
1140    fn read_vector_4_f32_from_vec_3_f32(&mut self) -> Result<Vector4<f32>> {
1141        let x = self.read_f32()?;
1142        let y = self.read_f32()?;
1143        let z = self.read_f32()?;
1144
1145        Ok(Vector4::new(x, y, z, 0.0))
1146    }
1147
1148    /// This function tries to read a Vector of 4 f32 normalized values from `self`.
1149    ///
1150    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1151    ///
1152    /// ```rust
1153    /// use nalgebra::Vector4;
1154    /// use std::io::Cursor;
1155    ///
1156    /// use rpfm_lib::binary::ReadBytes;
1157    ///
1158    /// let data = vec![0x0A, 0x0A, 0x0A, 0x0A];
1159    /// let mut cursor = Cursor::new(data);
1160    /// let data = cursor.read_vector_4_f32_normal_from_vector_4_u8().unwrap();
1161    ///
1162    /// assert_eq!(data, Vector4::new(-0.92156863, -0.92156863, -0.92156863, -0.92156863));
1163    /// assert_eq!(cursor.read_vector_4_f32_normal_from_vector_4_u8().is_err(), true);
1164    /// ```
1165    fn read_vector_4_f32_normal_from_vector_4_u8(&mut self) -> Result<Vector4<f32>> {
1166        let mut x = self.read_f32_normal_from_u8()?;
1167        let mut y = self.read_f32_normal_from_u8()?;
1168        let mut z = self.read_f32_normal_from_u8()?;
1169        let w = self.read_f32_normal_from_u8()?;
1170
1171        if w > 0.0 {
1172            x *= w;
1173            y *= w;
1174            z *= w;
1175        }
1176
1177        Ok(Vector4::new(x, y, z, w))
1178    }
1179
1180    /// This function tries to read a Vector of 4 f32 percentage values from `self`.
1181    ///
1182    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1183    ///
1184    /// ```rust
1185    /// use nalgebra::Vector4;
1186    /// use std::io::Cursor;
1187    ///
1188    /// use rpfm_lib::binary::ReadBytes;
1189    ///
1190    /// let data = vec![0x0A, 0x0A, 0x0A, 0x0A];
1191    /// let mut cursor = Cursor::new(data);
1192    /// let data = cursor.read_vector_4_f32_pct_from_vector_4_u8().unwrap();
1193    ///
1194    /// assert_eq!(data, Vector4::new(0.039215688, 0.039215688, 0.039215688, 0.039215688));
1195    /// assert_eq!(cursor.read_vector_4_f32_pct_from_vector_4_u8().is_err(), true);
1196    /// ```
1197    fn read_vector_4_f32_pct_from_vector_4_u8(&mut self) -> Result<Vector4<f32>> {
1198        let x = self.read_u8()? as f32;
1199        let y = self.read_u8()? as f32;
1200        let z = self.read_u8()? as f32;
1201        let w = self.read_u8()? as f32;
1202
1203        Ok(Vector4::new(x / 255.0, y / 255.0, z / 255.0, w / 255.0))
1204    }
1205
1206    /// This function tries to read a Vector of 4 f32 normalized values from `self`.
1207    ///
1208    /// It may fail if there are not enough bytes to read the value or `self` cannot be read.
1209    ///
1210    /// ```rust
1211    /// use nalgebra::Vector4;
1212    /// use std::io::Cursor;
1213    ///
1214    /// use rpfm_lib::binary::ReadBytes;
1215    ///
1216    /// let data = vec![
1217    ///     0x0A, 0x3F,
1218    ///     0x0A, 0x3F,
1219    ///     0x0A, 0x3F,
1220    ///     0x0A, 0x3F
1221    /// ];
1222    /// let mut cursor = Cursor::new(data);
1223    /// let data = cursor.read_vector_4_f32_normal_from_vector_4_f16().unwrap();
1224    ///
1225    /// assert_eq!(data, Vector4::new(3.096775, 3.096775, 3.096775, 1.7597656));
1226    /// assert_eq!(cursor.read_vector_4_f32_normal_from_vector_4_f16().is_err(), true);
1227    /// ```
1228    fn read_vector_4_f32_normal_from_vector_4_f16(&mut self) -> Result<Vector4<f32>> {
1229        let mut x = self.read_f16()?.to_f32();
1230        let mut y = self.read_f16()?.to_f32();
1231        let mut z = self.read_f16()?.to_f32();
1232        let w = self.read_f16()?.to_f32();
1233
1234        if w != 0.0 {
1235            x *= w;
1236            y *= w;
1237            z *= w;
1238        }
1239
1240        Ok(Vector4::new(x, y, z, w))
1241    }
1242}
1243
1244// Automatic implementation for everything that implements `Read + Seek`.
1245impl<R: Read + Seek> ReadBytes for R {}