]>
Commit | Line | Data |
---|---|---|
28884194 | 1 | //! Bytestream reading/writing functionality. |
37f2396b | 2 | pub use std::io::SeekFrom; |
90aa4e6b | 3 | use std::io::prelude::*; |
e243ceb4 | 4 | use std::ptr; |
90aa4e6b | 5 | |
28884194 | 6 | /// A list specifying general bytestream reading and writing errors. |
90aa4e6b KS |
7 | #[derive(Debug)] |
8 | pub enum ByteIOError { | |
28884194 | 9 | /// End of stream. |
90aa4e6b | 10 | EOF, |
28884194 | 11 | /// Wrong seek position was provided. |
90aa4e6b | 12 | WrongRange, |
28884194 | 13 | /// Tried to call read() on bytestream writer or write() on bytestream reader. |
90aa4e6b | 14 | WrongIOMode, |
28884194 | 15 | /// Functionality is not implemented. |
90aa4e6b | 16 | NotImplemented, |
28884194 | 17 | /// Read error. |
90aa4e6b | 18 | ReadError, |
28884194 | 19 | /// Write error. |
90aa4e6b | 20 | WriteError, |
28884194 | 21 | /// Seeking failed. |
90aa4e6b KS |
22 | SeekError, |
23 | } | |
24 | ||
28884194 | 25 | /// A specialised `Result` type for bytestream operations. |
296d86b2 | 26 | pub type ByteIOResult<T> = Result<T, ByteIOError>; |
90aa4e6b | 27 | |
28884194 | 28 | /// Common trait for bytestream operations. |
90aa4e6b | 29 | pub trait ByteIO { |
28884194 | 30 | /// Reads data into provided buffer. Fails if it cannot fill whole buffer. |
90aa4e6b | 31 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize>; |
28884194 | 32 | /// Reads data into provided buffer. Partial read is treated as success. |
89de616c | 33 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize>; |
28884194 | 34 | /// Reads data into provided buffer but does not advance read position. |
794364cf | 35 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize>; |
28884194 | 36 | /// Reads single byte from the stream. |
90aa4e6b | 37 | fn read_byte(&mut self) -> ByteIOResult<u8>; |
28884194 | 38 | /// Returns the next byte value in the stream without advancing read position. |
794364cf | 39 | fn peek_byte(&mut self) -> ByteIOResult<u8>; |
28884194 | 40 | /// Writes buffer to the stream. |
d532000c | 41 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()>; |
28884194 | 42 | /// Returns current read or write position. |
90aa4e6b | 43 | fn tell(&mut self) -> u64; |
28884194 | 44 | /// Seeks to the provided position. |
90aa4e6b | 45 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64>; |
28884194 | 46 | /// Tells whether this is end of stream. |
e243ceb4 | 47 | fn is_eof(&self) -> bool; |
28884194 | 48 | /// Reports whether stream is seekable or not. |
90aa4e6b | 49 | fn is_seekable(&mut self) -> bool; |
28884194 | 50 | /// Returns stream size or -1 if it is not known. |
d532000c | 51 | fn size(&mut self) -> i64; |
cf095d56 KS |
52 | /// Flushes output if possible. |
53 | fn flush(&mut self) -> ByteIOResult<()>; | |
90aa4e6b KS |
54 | } |
55 | ||
28884194 KS |
56 | /// High-level bytestream reader. |
57 | /// | |
58 | /// User is supposed to create some reader implementing [`ByteIO`] trait e.g. [`MemoryReader`] and use it to create `ByteReader` which can be used for reading e.g. various integer types. | |
59 | /// | |
60 | /// # Examples | |
61 | /// | |
62 | /// ```` | |
63 | /// use nihav_core::io::byteio::{MemoryReader,ByteReader}; | |
64 | /// # use nihav_core::io::byteio::ByteIOResult; | |
65 | /// | |
66 | /// # fn foo() -> ByteIOResult<()> { | |
67 | /// let memory: [u8; 4] = [ 0, 42, 42, 0 ]; | |
68 | /// let mut mr = MemoryReader::new_read(&memory); | |
69 | /// let mut br = ByteReader::new(&mut mr); | |
70 | /// let val = br.read_u16be()?; // read 16-bit big-endian integer, should be 42 | |
71 | /// let val = br.read_u16le()?; // read 16-bit little-endian integer, should be 42 as well | |
72 | /// # Ok(()) | |
73 | /// # } | |
74 | /// ```` | |
75 | /// | |
76 | /// [`ByteIO`]: ./trait.ByteIO.html | |
77 | /// [`MemoryReader`]: ./struct.MemoryReader.html | |
90aa4e6b KS |
78 | #[allow(dead_code)] |
79 | pub struct ByteReader<'a> { | |
ac818eac | 80 | io: &'a mut dyn ByteIO, |
90aa4e6b KS |
81 | } |
82 | ||
28884194 | 83 | /// Bytestream reader from memory. |
90aa4e6b KS |
84 | pub struct MemoryReader<'a> { |
85 | buf: &'a [u8], | |
90aa4e6b | 86 | pos: usize, |
90aa4e6b KS |
87 | } |
88 | ||
789354a8 KS |
89 | /// Bytestream reader from anything implementing `std::io::Read` and `std::io::Seek`. |
90 | pub struct FileReader<T: Read+Seek> { | |
91 | file: Box<T>, | |
90aa4e6b KS |
92 | eof: bool, |
93 | } | |
94 | ||
a91a8367 KS |
95 | /// Bytestream reader from anything implementing `std::io::Read` and `std::io::Seek` that operates only on a part of the input. |
96 | pub struct BoundedFileReader<T: Read+Seek> { | |
97 | file: Box<T>, | |
98 | start: u64, | |
99 | end: Option<u64>, | |
100 | eof: bool, | |
101 | } | |
102 | ||
90aa4e6b KS |
103 | macro_rules! read_int { |
104 | ($s: ident, $inttype: ty, $size: expr, $which: ident) => ({ | |
90aa4e6b | 105 | unsafe { |
e243ceb4 KS |
106 | let mut buf: $inttype = 0; |
107 | $s.read_buf(&mut *(&mut buf as *mut $inttype as *mut [u8; $size]))?; | |
108 | Ok(buf.$which()) | |
90aa4e6b KS |
109 | } |
110 | }) | |
111 | } | |
112 | ||
794364cf KS |
113 | macro_rules! peek_int { |
114 | ($s: ident, $inttype: ty, $size: expr, $which: ident) => ({ | |
794364cf | 115 | unsafe { |
e243ceb4 KS |
116 | let mut buf: $inttype = 0; |
117 | $s.peek_buf(&mut *(&mut buf as *mut $inttype as *mut [u8; $size]))?; | |
118 | Ok(buf.$which()) | |
794364cf KS |
119 | } |
120 | }) | |
121 | } | |
122 | ||
95058bc1 KS |
123 | macro_rules! read_int_func { |
124 | ($s: ident, $inttype: ty, $size: expr, $which: ident) => { | |
28884194 | 125 | /// Reads integer of certain size and endianness. |
95058bc1 KS |
126 | pub fn $s(src: &[u8]) -> ByteIOResult<$inttype> { |
127 | if src.len() < $size { return Err(ByteIOError::ReadError); } | |
128 | unsafe { | |
e243ceb4 | 129 | let mut buf: $inttype = 0; |
c9087a4c | 130 | ptr::copy_nonoverlapping(src.as_ptr(), &mut buf as *mut $inttype as *mut u8, std::mem::size_of::<$inttype>()); |
e243ceb4 | 131 | Ok(buf.$which()) |
95058bc1 KS |
132 | } |
133 | } | |
134 | } | |
135 | } | |
136 | ||
137 | read_int_func!(read_u16be, u16, 2, to_be); | |
138 | read_int_func!(read_u16le, u16, 2, to_le); | |
139 | read_int_func!(read_u32be, u32, 4, to_be); | |
140 | read_int_func!(read_u32le, u32, 4, to_le); | |
141 | read_int_func!(read_u64be, u64, 8, to_be); | |
142 | read_int_func!(read_u64le, u64, 8, to_le); | |
143 | ||
28884194 KS |
144 | /// Reads 24-bit big-endian integer. |
145 | /// | |
146 | /// # Example | |
147 | /// | |
148 | /// ```` | |
149 | /// use nihav_core::io::byteio::read_u24be; | |
150 | /// # use nihav_core::io::byteio::ByteIOResult; | |
151 | /// | |
152 | /// # fn foo() -> ByteIOResult<()> { | |
153 | /// let src: [u8; 3] = [ 1, 2, 3]; | |
154 | /// let value = read_u24be(&src)?; // should return 0x010203 | |
155 | /// # Ok(()) | |
156 | /// # } | |
157 | /// ```` | |
95058bc1 KS |
158 | pub fn read_u24be(src: &[u8]) -> ByteIOResult<u32> { |
159 | if src.len() < 3 { return Err(ByteIOError::ReadError); } | |
e243ceb4 | 160 | Ok((u32::from(src[0]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[2])) |
95058bc1 | 161 | } |
28884194 | 162 | /// Reads 24-bit little-endian integer. |
95058bc1 KS |
163 | pub fn read_u24le(src: &[u8]) -> ByteIOResult<u32> { |
164 | if src.len() < 3 { return Err(ByteIOError::ReadError); } | |
e243ceb4 | 165 | Ok((u32::from(src[2]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[0])) |
95058bc1 | 166 | } |
28884194 | 167 | /// Reads 32-bit big-endian floating point number. |
02a5bdaf | 168 | pub fn read_f32be(src: &[u8]) -> ByteIOResult<f32> { Ok(f32::from_bits(read_u32be(src)?)) } |
28884194 | 169 | /// Reads 32-bit little-endian floating point number. |
02a5bdaf | 170 | pub fn read_f32le(src: &[u8]) -> ByteIOResult<f32> { Ok(f32::from_bits(read_u32le(src)?)) } |
28884194 | 171 | /// Reads 64-bit big-endian floating point number. |
02a5bdaf | 172 | pub fn read_f64be(src: &[u8]) -> ByteIOResult<f64> { Ok(f64::from_bits(read_u64be(src)?)) } |
28884194 | 173 | /// Reads 64-bit little-endian floating point number. |
02a5bdaf | 174 | pub fn read_f64le(src: &[u8]) -> ByteIOResult<f64> { Ok(f64::from_bits(read_u64le(src)?)) } |
95058bc1 | 175 | |
95c7f2f6 KS |
176 | macro_rules! write_int_func { |
177 | ($s: ident, $inttype: ty, $size: expr, $which: ident) => { | |
28884194 | 178 | /// Writes integer of certain size and endianness into byte buffer. |
95c7f2f6 KS |
179 | pub fn $s(dst: &mut [u8], val: $inttype) -> ByteIOResult<()> { |
180 | if dst.len() < $size { return Err(ByteIOError::WriteError); } | |
181 | unsafe { | |
182 | let val = val.$which(); | |
183 | ptr::copy_nonoverlapping(&val as *const $inttype as *const u8, dst.as_mut_ptr(), std::mem::size_of::<$inttype>()); | |
184 | } | |
185 | Ok(()) | |
186 | } | |
187 | } | |
188 | } | |
189 | ||
190 | write_int_func!(write_u16be, u16, 2, to_be); | |
191 | write_int_func!(write_u16le, u16, 2, to_le); | |
192 | write_int_func!(write_u32be, u32, 4, to_be); | |
193 | write_int_func!(write_u32le, u32, 4, to_le); | |
194 | write_int_func!(write_u64be, u64, 8, to_be); | |
195 | write_int_func!(write_u64le, u64, 8, to_le); | |
196 | ||
28884194 KS |
197 | /// Writes 24-bit big-endian integer to the provided buffer. |
198 | /// | |
199 | /// # Example | |
200 | /// | |
201 | /// ```` | |
202 | /// use nihav_core::io::byteio::write_u24be; | |
203 | /// # use nihav_core::io::byteio::ByteIOResult; | |
204 | /// | |
205 | /// # fn foo() -> ByteIOResult<()> { | |
206 | /// let mut dst = [0u8; 3]; | |
207 | /// write_u24be(&mut dst, 0x010203)?; | |
208 | /// // dst should contain [ 1, 2, 3] now | |
209 | /// # Ok(()) | |
210 | /// # } | |
211 | /// ```` | |
b36f412c | 212 | #[allow(clippy::identity_op)] |
95c7f2f6 KS |
213 | pub fn write_u24be(dst: &mut [u8], val: u32) -> ByteIOResult<()> { |
214 | if dst.len() < 3 { return Err(ByteIOError::WriteError); } | |
215 | dst[0] = (val >> 16) as u8; | |
216 | dst[1] = (val >> 8) as u8; | |
217 | dst[2] = (val >> 0) as u8; | |
218 | Ok(()) | |
219 | } | |
28884194 | 220 | /// Writes 24-bit little-endian integer to the provided buffer. |
b36f412c | 221 | #[allow(clippy::identity_op)] |
95c7f2f6 KS |
222 | pub fn write_u24le(dst: &mut [u8], val: u32) -> ByteIOResult<()> { |
223 | if dst.len() < 3 { return Err(ByteIOError::WriteError); } | |
224 | dst[0] = (val >> 0) as u8; | |
225 | dst[1] = (val >> 8) as u8; | |
226 | dst[2] = (val >> 16) as u8; | |
227 | Ok(()) | |
228 | } | |
28884194 | 229 | /// Writes 32-bit big-endian floating point number to the provided buffer. |
02a5bdaf | 230 | pub fn write_f32be(dst: &mut [u8], val: f32) -> ByteIOResult<()> { write_u32be(dst, val.to_bits()) } |
28884194 | 231 | /// Writes 32-bit little-endian floating point number to the provided buffer. |
02a5bdaf | 232 | pub fn write_f32le(dst: &mut [u8], val: f32) -> ByteIOResult<()> { write_u32le(dst, val.to_bits()) } |
28884194 | 233 | /// Writes 64-bit big-endian floating point number to the provided buffer. |
02a5bdaf | 234 | pub fn write_f64be(dst: &mut [u8], val: f64) -> ByteIOResult<()> { write_u64be(dst, val.to_bits()) } |
28884194 | 235 | /// Writes 64-bit little-endian floating point number to the provided buffer. |
02a5bdaf | 236 | pub fn write_f64le(dst: &mut [u8], val: f64) -> ByteIOResult<()> { write_u64le(dst, val.to_bits()) } |
95c7f2f6 | 237 | |
90aa4e6b | 238 | impl<'a> ByteReader<'a> { |
28884194 KS |
239 | /// Constructs a new instance of bytestream reader. |
240 | /// | |
241 | /// # Examples | |
242 | /// | |
243 | /// ```` | |
244 | /// use nihav_core::io::byteio::{MemoryReader,ByteReader}; | |
245 | /// # use nihav_core::io::byteio::ByteIOResult; | |
246 | /// | |
247 | /// # fn foo() -> ByteIOResult<()> { | |
248 | /// let memory: [u8; 4] = [ 0, 42, 42, 0 ]; | |
249 | /// let mut mr = MemoryReader::new_read(&memory); | |
250 | /// let mut br = ByteReader::new(&mut mr); | |
251 | /// # Ok(()) | |
252 | /// # } | |
253 | /// ```` | |
ac818eac | 254 | pub fn new(io: &'a mut dyn ByteIO) -> Self { ByteReader { io } } |
90aa4e6b | 255 | |
28884194 | 256 | /// Reads data into provided buffer. Partial read is treated as success. |
90aa4e6b KS |
257 | pub fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
258 | self.io.read_buf(buf) | |
259 | } | |
260 | ||
28884194 | 261 | /// Reads data into provided buffer. Partial read is treated as success. |
89de616c KS |
262 | pub fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
263 | self.io.read_buf_some(buf) | |
264 | } | |
265 | ||
28884194 | 266 | /// Reads data into provided buffer but does not advance read position. |
794364cf KS |
267 | pub fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
268 | self.io.peek_buf(buf) | |
269 | } | |
270 | ||
28884194 | 271 | /// Reads single byte from the stream. |
90aa4e6b KS |
272 | pub fn read_byte(&mut self) -> ByteIOResult<u8> { |
273 | self.io.read_byte() | |
274 | } | |
275 | ||
28884194 | 276 | /// Returns the next byte value in the stream without advancing read position. |
794364cf KS |
277 | pub fn peek_byte(&mut self) -> ByteIOResult<u8> { |
278 | self.io.peek_byte() | |
279 | } | |
280 | ||
943d7b14 KS |
281 | /// Reads four-byte array from the stream. |
282 | pub fn read_tag(&mut self) -> ByteIOResult<[u8; 4]> { | |
283 | let mut buf = [0u8; 4]; | |
284 | self.io.read_buf(&mut buf)?; | |
285 | Ok(buf) | |
286 | } | |
287 | ||
288 | /// Reads four-byte array from the stream without advancing read position. | |
289 | pub fn peek_tag(&mut self) -> ByteIOResult<[u8; 4]> { | |
290 | let mut buf = [0u8; 4]; | |
291 | self.io.peek_buf(&mut buf)?; | |
292 | Ok(buf) | |
293 | } | |
294 | ||
28884194 | 295 | /// Reads 16-bit big-endian integer from the stream. |
90aa4e6b KS |
296 | pub fn read_u16be(&mut self) -> ByteIOResult<u16> { |
297 | read_int!(self, u16, 2, to_be) | |
298 | } | |
299 | ||
28884194 | 300 | /// Reads 16-bit big-endian integer from the stream without advancing read position. |
794364cf KS |
301 | pub fn peek_u16be(&mut self) -> ByteIOResult<u16> { |
302 | peek_int!(self, u16, 2, to_be) | |
303 | } | |
304 | ||
28884194 | 305 | /// Reads 24-bit big-endian integer from the stream. |
90aa4e6b | 306 | pub fn read_u24be(&mut self) -> ByteIOResult<u32> { |
794364cf KS |
307 | let p16 = self.read_u16be()?; |
308 | let p8 = self.read_byte()?; | |
e243ceb4 | 309 | Ok((u32::from(p16) << 8) | u32::from(p8)) |
794364cf KS |
310 | } |
311 | ||
28884194 | 312 | /// Reads 24-bit big-endian integer from the stream without advancing read position. |
794364cf KS |
313 | pub fn peek_u24be(&mut self) -> ByteIOResult<u32> { |
314 | let mut src: [u8; 3] = [0; 3]; | |
315 | self.peek_buf(&mut src)?; | |
e243ceb4 | 316 | Ok((u32::from(src[0]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[2])) |
90aa4e6b KS |
317 | } |
318 | ||
28884194 | 319 | /// Reads 32-bit big-endian integer from the stream. |
90aa4e6b KS |
320 | pub fn read_u32be(&mut self) -> ByteIOResult<u32> { |
321 | read_int!(self, u32, 4, to_be) | |
322 | } | |
323 | ||
28884194 | 324 | /// Reads 32-bit big-endian integer from the stream without advancing read position. |
794364cf KS |
325 | pub fn peek_u32be(&mut self) -> ByteIOResult<u32> { |
326 | peek_int!(self, u32, 4, to_be) | |
327 | } | |
328 | ||
28884194 | 329 | /// Reads 64-bit big-endian integer from the stream. |
90aa4e6b KS |
330 | pub fn read_u64be(&mut self) -> ByteIOResult<u64> { |
331 | read_int!(self, u64, 8, to_be) | |
332 | } | |
333 | ||
28884194 | 334 | /// Reads 64-bit big-endian integer from the stream without advancing read position. |
794364cf KS |
335 | pub fn peek_u64be(&mut self) -> ByteIOResult<u64> { |
336 | peek_int!(self, u64, 8, to_be) | |
337 | } | |
338 | ||
28884194 | 339 | /// Reads 32-bit big-endian floating point number from the stream. |
02a5bdaf KS |
340 | pub fn read_f32be(&mut self) -> ByteIOResult<f32> { |
341 | Ok(f32::from_bits(self.read_u32be()?)) | |
342 | } | |
343 | ||
28884194 | 344 | /// Reads 32-bit big-endian floating point number from the stream without advancing read position. |
02a5bdaf KS |
345 | pub fn peek_f32be(&mut self) -> ByteIOResult<f32> { |
346 | Ok(f32::from_bits(self.peek_u32be()?)) | |
347 | } | |
348 | ||
28884194 | 349 | /// Reads 64-bit big-endian floating point number from the stream. |
02a5bdaf KS |
350 | pub fn read_f64be(&mut self) -> ByteIOResult<f64> { |
351 | Ok(f64::from_bits(self.read_u64be()?)) | |
352 | } | |
353 | ||
28884194 | 354 | /// Reads 64-bit big-endian floating point number from the stream without advancing read position. |
02a5bdaf KS |
355 | pub fn peek_f64be(&mut self) -> ByteIOResult<f64> { |
356 | Ok(f64::from_bits(self.peek_u64be()?)) | |
357 | } | |
358 | ||
28884194 | 359 | /// Reads 16-bit little-endian integer from the stream. |
90aa4e6b KS |
360 | pub fn read_u16le(&mut self) -> ByteIOResult<u16> { |
361 | read_int!(self, u16, 2, to_le) | |
362 | } | |
363 | ||
28884194 | 364 | /// Reads 16-bit little-endian integer from the stream without advancing read position. |
794364cf KS |
365 | pub fn peek_u16le(&mut self) -> ByteIOResult<u16> { |
366 | peek_int!(self, u16, 2, to_le) | |
367 | } | |
368 | ||
28884194 | 369 | /// Reads 24-bit little-endian integer from the stream. |
90aa4e6b | 370 | pub fn read_u24le(&mut self) -> ByteIOResult<u32> { |
794364cf KS |
371 | let p8 = self.read_byte()?; |
372 | let p16 = self.read_u16le()?; | |
e243ceb4 | 373 | Ok((u32::from(p16) << 8) | u32::from(p8)) |
794364cf KS |
374 | } |
375 | ||
28884194 | 376 | /// Reads 24-bit little-endian integer from the stream without advancing read position. |
794364cf KS |
377 | pub fn peek_u24le(&mut self) -> ByteIOResult<u32> { |
378 | let mut src: [u8; 3] = [0; 3]; | |
379 | self.peek_buf(&mut src)?; | |
e243ceb4 | 380 | Ok(u32::from(src[0]) | (u32::from(src[1]) << 8) | (u32::from(src[2]) << 16)) |
90aa4e6b KS |
381 | } |
382 | ||
28884194 | 383 | /// Reads 32-bit little-endian integer from the stream. |
90aa4e6b KS |
384 | pub fn read_u32le(&mut self) -> ByteIOResult<u32> { |
385 | read_int!(self, u32, 4, to_le) | |
386 | } | |
387 | ||
28884194 | 388 | /// Reads 32-bit little-endian integer from the stream without advancing read position. |
794364cf KS |
389 | pub fn peek_u32le(&mut self) -> ByteIOResult<u32> { |
390 | peek_int!(self, u32, 4, to_le) | |
391 | } | |
392 | ||
28884194 | 393 | /// Reads 64-bit little-endian integer from the stream. |
90aa4e6b KS |
394 | pub fn read_u64le(&mut self) -> ByteIOResult<u64> { |
395 | read_int!(self, u64, 8, to_le) | |
396 | } | |
397 | ||
28884194 | 398 | /// Reads 64-bit little-endian integer from the stream without advancing read position. |
794364cf KS |
399 | pub fn peek_u64le(&mut self) -> ByteIOResult<u64> { |
400 | peek_int!(self, u64, 8, to_le) | |
401 | } | |
402 | ||
28884194 | 403 | /// Reads 32-bit little-endian floating point number from the stream. |
02a5bdaf KS |
404 | pub fn read_f32le(&mut self) -> ByteIOResult<f32> { |
405 | Ok(f32::from_bits(self.read_u32le()?)) | |
406 | } | |
407 | ||
28884194 | 408 | /// Reads 32-bit little-endian floating point number from the stream without advancing read position. |
02a5bdaf KS |
409 | pub fn peek_f32le(&mut self) -> ByteIOResult<f32> { |
410 | Ok(f32::from_bits(self.peek_u32le()?)) | |
411 | } | |
412 | ||
28884194 | 413 | /// Reads 64-bit little-endian floating point number from the stream. |
02a5bdaf KS |
414 | pub fn read_f64le(&mut self) -> ByteIOResult<f64> { |
415 | Ok(f64::from_bits(self.read_u64le()?)) | |
416 | } | |
417 | ||
28884194 | 418 | /// Reads 64-bit little-endian floating point number from the stream without advancing read position. |
02a5bdaf KS |
419 | pub fn peek_f64le(&mut self) -> ByteIOResult<f64> { |
420 | Ok(f64::from_bits(self.peek_u64le()?)) | |
421 | } | |
422 | ||
28884194 | 423 | /// Skips requested number of bytes. |
6b167b0c | 424 | pub fn read_skip(&mut self, len: usize) -> ByteIOResult<()> { |
90aa4e6b KS |
425 | if self.io.is_seekable() { |
426 | self.io.seek(SeekFrom::Current(len as i64))?; | |
427 | } else { | |
428 | let mut ssize = len; | |
429 | let mut buf : [u8; 16] = [0; 16]; | |
9037cf6b | 430 | let bref = &mut buf; |
90aa4e6b KS |
431 | while ssize > bref.len() { |
432 | self.io.read_buf(bref)?; | |
433 | ssize -= bref.len(); | |
434 | } | |
435 | while ssize > 0 { | |
436 | self.io.read_byte()?; | |
e243ceb4 | 437 | ssize -= 1; |
90aa4e6b KS |
438 | } |
439 | } | |
6b167b0c | 440 | Ok(()) |
90aa4e6b KS |
441 | } |
442 | ||
28884194 | 443 | /// Returns current read position. |
90aa4e6b KS |
444 | pub fn tell(&mut self) -> u64 { |
445 | self.io.tell() | |
446 | } | |
447 | ||
28884194 | 448 | /// Seeks to the provided position. |
90aa4e6b KS |
449 | pub fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { |
450 | self.io.seek(pos) | |
451 | } | |
452 | ||
28884194 | 453 | /// Tells whether this is end of stream. |
e243ceb4 | 454 | pub fn is_eof(&self) -> bool { |
90aa4e6b KS |
455 | self.io.is_eof() |
456 | } | |
96c6be97 | 457 | |
28884194 | 458 | /// Returns stream size or -1 if it is not known. |
96c6be97 KS |
459 | pub fn size(&mut self) -> i64 { |
460 | self.io.size() | |
461 | } | |
462 | ||
28884194 | 463 | /// Reports number of bytes left in the stream. |
96c6be97 KS |
464 | pub fn left(&mut self) -> i64 { |
465 | let size = self.io.size(); | |
466 | if size == -1 { return -1; } | |
e243ceb4 | 467 | size - (self.io.tell() as i64) |
96c6be97 | 468 | } |
90aa4e6b KS |
469 | } |
470 | ||
471 | impl<'a> MemoryReader<'a> { | |
28884194 | 472 | /// Constructs a new instance of `MemoryReader`. |
90aa4e6b | 473 | pub fn new_read(buf: &'a [u8]) -> Self { |
1be85e00 | 474 | MemoryReader { buf, pos: 0 } |
90aa4e6b KS |
475 | } |
476 | ||
477 | fn real_seek(&mut self, pos: i64) -> ByteIOResult<u64> { | |
1be85e00 | 478 | if pos < 0 || (pos as usize) > self.buf.len() { |
e243ceb4 | 479 | return Err(ByteIOError::WrongRange); |
90aa4e6b KS |
480 | } |
481 | self.pos = pos as usize; | |
482 | Ok(pos as u64) | |
483 | } | |
90aa4e6b KS |
484 | } |
485 | ||
486 | impl<'a> ByteIO for MemoryReader<'a> { | |
487 | fn read_byte(&mut self) -> ByteIOResult<u8> { | |
90aa4e6b KS |
488 | if self.is_eof() { return Err(ByteIOError::EOF); } |
489 | let res = self.buf[self.pos]; | |
e243ceb4 | 490 | self.pos += 1; |
90aa4e6b KS |
491 | Ok(res) |
492 | } | |
493 | ||
794364cf KS |
494 | fn peek_byte(&mut self) -> ByteIOResult<u8> { |
495 | if self.is_eof() { return Err(ByteIOError::EOF); } | |
496 | Ok(self.buf[self.pos]) | |
497 | } | |
498 | ||
499 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
b2939bd8 | 500 | let copy_size = if self.buf.len() - self.pos < buf.len() { self.buf.len() - self.pos } else { buf.len() }; |
90aa4e6b | 501 | if copy_size == 0 { return Err(ByteIOError::EOF); } |
e243ceb4 KS |
502 | let dst = &mut buf[0..copy_size]; |
503 | dst.copy_from_slice(&self.buf[self.pos..][..copy_size]); | |
90aa4e6b KS |
504 | Ok(copy_size) |
505 | } | |
506 | ||
794364cf | 507 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
89de616c KS |
508 | let read_size = self.peek_buf(buf)?; |
509 | if read_size < buf.len() { return Err(ByteIOError::EOF); } | |
510 | self.pos += read_size; | |
511 | Ok(read_size) | |
512 | } | |
513 | ||
514 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
794364cf KS |
515 | let read_size = self.peek_buf(buf)?; |
516 | self.pos += read_size; | |
517 | Ok(read_size) | |
518 | } | |
519 | ||
90aa4e6b | 520 | #[allow(unused_variables)] |
d532000c | 521 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { |
90aa4e6b KS |
522 | Err(ByteIOError::NotImplemented) |
523 | } | |
524 | ||
525 | fn tell(&mut self) -> u64 { | |
526 | self.pos as u64 | |
527 | } | |
528 | ||
529 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
1be85e00 KS |
530 | let cur_pos = self.pos as i64; |
531 | let cur_size = self.buf.len() as i64; | |
90aa4e6b KS |
532 | match pos { |
533 | SeekFrom::Start(x) => self.real_seek(x as i64), | |
534 | SeekFrom::Current(x) => self.real_seek(cur_pos + x), | |
535 | SeekFrom::End(x) => self.real_seek(cur_size + x), | |
536 | } | |
537 | } | |
538 | ||
e243ceb4 | 539 | fn is_eof(&self) -> bool { |
1be85e00 | 540 | self.pos >= self.buf.len() |
90aa4e6b KS |
541 | } |
542 | ||
543 | fn is_seekable(&mut self) -> bool { | |
544 | true | |
545 | } | |
d532000c KS |
546 | |
547 | fn size(&mut self) -> i64 { | |
548 | self.buf.len() as i64 | |
549 | } | |
cf095d56 KS |
550 | |
551 | fn flush(&mut self) -> ByteIOResult<()> { Ok(()) } | |
90aa4e6b KS |
552 | } |
553 | ||
789354a8 | 554 | impl<T: Read+Seek> FileReader<T> { |
90aa4e6b | 555 | |
28884194 | 556 | /// Constructs a new instance of `FileReader`. |
789354a8 KS |
557 | pub fn new_read(file: T) -> Self { |
558 | FileReader { file: Box::new(file), eof : false } | |
90aa4e6b | 559 | } |
dee2d2f1 KS |
560 | /// Constructs a new instance of `FileReader` using a boxed resource. |
561 | pub fn new_read_boxed(file: Box<T>) -> Self { | |
562 | FileReader { file, eof : false } | |
563 | } | |
564 | /// Destroys the reader and releases the reader resource for a further use. | |
565 | pub fn finish(self) -> Box<T> { self.file } | |
90aa4e6b KS |
566 | } |
567 | ||
789354a8 | 568 | impl<T: Read+Seek> ByteIO for FileReader<T> { |
90aa4e6b KS |
569 | fn read_byte(&mut self) -> ByteIOResult<u8> { |
570 | let mut byte : [u8; 1] = [0]; | |
e243ceb4 KS |
571 | let ret = self.file.read(&mut byte); |
572 | if ret.is_err() { return Err(ByteIOError::ReadError); } | |
573 | let sz = ret.unwrap(); | |
90aa4e6b KS |
574 | if sz == 0 { self.eof = true; return Err(ByteIOError::EOF); } |
575 | Ok (byte[0]) | |
576 | } | |
577 | ||
794364cf KS |
578 | fn peek_byte(&mut self) -> ByteIOResult<u8> { |
579 | let b = self.read_byte()?; | |
580 | self.seek(SeekFrom::Current(-1))?; | |
581 | Ok(b) | |
582 | } | |
583 | ||
90aa4e6b | 584 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
6c0356da KS |
585 | match self.file.read_exact(buf) { |
586 | Ok(()) => Ok(buf.len()), | |
587 | Err(err) => { | |
588 | if err.kind() == std::io::ErrorKind::UnexpectedEof { | |
589 | self.eof = true; | |
590 | Err(ByteIOError::EOF) | |
591 | } else { | |
592 | Err(ByteIOError::ReadError) | |
593 | } | |
594 | }, | |
595 | } | |
89de616c KS |
596 | } |
597 | ||
598 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
e243ceb4 KS |
599 | let ret = self.file.read(buf); |
600 | if ret.is_err() { return Err(ByteIOError::ReadError); } | |
601 | let sz = ret.unwrap(); | |
6c0356da | 602 | if sz < buf.len() { |
f88724a8 | 603 | if let Err(_err) = self.file.read_exact(&mut buf[sz..][..1]) { |
6c0356da | 604 | self.eof = true; |
f88724a8 KS |
605 | if sz == 0 { |
606 | return Err(ByteIOError::EOF); | |
607 | } | |
6c0356da KS |
608 | } else { |
609 | return Ok(sz + 1); | |
610 | } | |
611 | } | |
90aa4e6b KS |
612 | Ok(sz) |
613 | } | |
614 | ||
794364cf KS |
615 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { |
616 | let size = self.read_buf(buf)?; | |
617 | self.seek(SeekFrom::Current(-(size as i64)))?; | |
618 | Ok(size) | |
619 | } | |
620 | ||
90aa4e6b | 621 | #[allow(unused_variables)] |
d532000c | 622 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { |
90aa4e6b KS |
623 | Err(ByteIOError::NotImplemented) |
624 | } | |
625 | ||
626 | fn tell(&mut self) -> u64 { | |
627 | self.file.seek(SeekFrom::Current(0)).unwrap() | |
628 | } | |
629 | ||
630 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
631 | let res = self.file.seek(pos); | |
632 | match res { | |
633 | Ok(r) => Ok(r), | |
634 | Err(_) => Err(ByteIOError::SeekError), | |
635 | } | |
636 | } | |
637 | ||
e243ceb4 | 638 | fn is_eof(&self) -> bool { |
90aa4e6b KS |
639 | self.eof |
640 | } | |
641 | ||
642 | fn is_seekable(&mut self) -> bool { | |
643 | true | |
644 | } | |
d532000c KS |
645 | |
646 | fn size(&mut self) -> i64 { | |
647 | -1 | |
648 | } | |
cf095d56 KS |
649 | |
650 | fn flush(&mut self) -> ByteIOResult<()> { Ok(()) } | |
d532000c KS |
651 | } |
652 | ||
a91a8367 KS |
653 | |
654 | impl<T: Read+Seek> BoundedFileReader<T> { | |
655 | ||
656 | /// Constructs a new instance of `BoundedFileReader`. The reader pretends that data before `start` and after `end` (if set) does not exist. | |
657 | pub fn new_read(file: T, start: u64, end: Option<u64>) -> ByteIOResult<Self> { | |
658 | let mut file = Box::new(file); | |
659 | if let Some(epos) = end { | |
660 | if start > epos { | |
661 | return Err(ByteIOError::WrongRange); | |
662 | } | |
663 | } | |
664 | if start > 0 && file.seek(SeekFrom::Start(start)).is_err() { | |
665 | return Err(ByteIOError::SeekError); | |
666 | } | |
667 | Ok(Self { file, start, end, eof : false }) | |
668 | } | |
669 | /// Constructs a new instance of `BoundedFileReader` using a boxed resource. The reader pretends that data before `start` and after `end` (if set) does not exist. | |
670 | pub fn new_read_boxed(mut file: Box<T>, start: u64, end: Option<u64>) -> ByteIOResult<Self> { | |
671 | if let Some(epos) = end { | |
672 | if start > epos { | |
673 | return Err(ByteIOError::WrongRange); | |
674 | } | |
675 | } | |
676 | if start > 0 && file.seek(SeekFrom::Start(start)).is_err() { | |
677 | return Err(ByteIOError::SeekError); | |
678 | } | |
679 | Ok(Self { file, start, end, eof : false }) | |
680 | } | |
681 | /// Destroys the reader and releases the reader resource for a further use. | |
682 | pub fn finish(self) -> Box<T> { self.file } | |
683 | fn real_tell(&mut self) -> u64 { | |
684 | self.file.seek(SeekFrom::Current(0)).unwrap() | |
685 | } | |
686 | fn max_read_len(&mut self, len: usize) -> usize { | |
687 | if let Some(epos) = self.end { | |
688 | (len as u64).min(epos - self.real_tell()) as usize | |
689 | } else { | |
690 | len | |
691 | } | |
692 | } | |
693 | } | |
694 | ||
695 | impl<T: Read+Seek> ByteIO for BoundedFileReader<T> { | |
696 | fn read_byte(&mut self) -> ByteIOResult<u8> { | |
697 | if let Some(epos) = self.end { | |
698 | if self.real_tell() >= epos { | |
699 | self.eof = true; | |
700 | return Err(ByteIOError::EOF); | |
701 | } | |
702 | } | |
703 | let mut byte : [u8; 1] = [0]; | |
704 | let ret = self.file.read(&mut byte); | |
705 | if ret.is_err() { return Err(ByteIOError::ReadError); } | |
706 | let sz = ret.unwrap(); | |
707 | if sz == 0 { self.eof = true; return Err(ByteIOError::EOF); } | |
708 | Ok (byte[0]) | |
709 | } | |
710 | ||
711 | fn peek_byte(&mut self) -> ByteIOResult<u8> { | |
712 | let b = self.read_byte()?; | |
713 | if self.file.seek(SeekFrom::Current(-1)).is_err() { | |
714 | return Err(ByteIOError::SeekError); | |
715 | } | |
716 | Ok(b) | |
717 | } | |
718 | ||
719 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
52f954a3 KS |
720 | if let Some(epos) = self.end { |
721 | if self.real_tell() >= epos { | |
722 | self.eof = true; | |
723 | return Err(ByteIOError::EOF); | |
724 | } | |
725 | } | |
a91a8367 KS |
726 | let len = self.max_read_len(buf.len()); |
727 | match self.file.read_exact(&mut buf[..len]) { | |
728 | Ok(()) if len == buf.len() => Ok(buf.len()), | |
729 | Ok(()) => { | |
730 | self.eof = true; | |
731 | Err(ByteIOError::EOF) | |
732 | }, | |
733 | Err(err) => { | |
734 | if err.kind() == std::io::ErrorKind::UnexpectedEof { | |
735 | self.eof = true; | |
736 | Err(ByteIOError::EOF) | |
737 | } else { | |
738 | Err(ByteIOError::ReadError) | |
739 | } | |
740 | }, | |
741 | } | |
742 | } | |
743 | ||
744 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
52f954a3 KS |
745 | if let Some(epos) = self.end { |
746 | if self.real_tell() >= epos { | |
747 | self.eof = true; | |
748 | return Err(ByteIOError::EOF); | |
749 | } | |
750 | } | |
a91a8367 KS |
751 | let len = self.max_read_len(buf.len()); |
752 | let ret = self.file.read(&mut buf[..len]); | |
753 | if ret.is_err() { return Err(ByteIOError::ReadError); } | |
754 | let sz = ret.unwrap(); | |
755 | if sz < len { | |
6a97ae3a | 756 | if let Ok(1) = self.file.read(&mut buf[sz..][..1]) { |
a91a8367 KS |
757 | return Ok(sz + 1); |
758 | } | |
6a97ae3a KS |
759 | self.eof = true; |
760 | if sz == 0 { | |
761 | return Err(ByteIOError::EOF); | |
762 | } | |
a91a8367 KS |
763 | } |
764 | Ok(sz) | |
765 | } | |
766 | ||
767 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
768 | let len = self.max_read_len(buf.len()); | |
769 | let size = self.read_buf(&mut buf[..len])?; | |
770 | if self.file.seek(SeekFrom::Current(-(size as i64))).is_err() { | |
771 | return Err(ByteIOError::SeekError); | |
772 | } | |
773 | Ok(size) | |
774 | } | |
775 | ||
776 | #[allow(unused_variables)] | |
777 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { | |
778 | Err(ByteIOError::NotImplemented) | |
779 | } | |
780 | ||
781 | fn tell(&mut self) -> u64 { | |
782 | self.file.seek(SeekFrom::Current(0)).unwrap() - self.start | |
783 | } | |
784 | ||
785 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
786 | let res = match pos { | |
787 | SeekFrom::Start(off) => { | |
788 | let dpos = self.start + off; | |
789 | if let Some(epos) = self.end { | |
790 | if dpos > epos { | |
791 | return Err(ByteIOError::WrongRange); | |
792 | } | |
793 | } | |
794 | self.file.seek(SeekFrom::Start(dpos)) | |
795 | }, | |
796 | SeekFrom::Current(off) => { | |
797 | let dpos = (self.real_tell() as i64) + off; | |
798 | let end = self.end.unwrap_or(dpos as u64); | |
799 | if dpos < 0 || ((dpos as u64) < self.start) || ((dpos as u64) > end) { | |
800 | return Err(ByteIOError::WrongRange); | |
801 | } | |
802 | self.file.seek(pos) | |
803 | }, | |
804 | SeekFrom::End(off) => { | |
805 | if let Some(epos) = self.end { | |
806 | let dpos = (epos as i64) + off; | |
807 | if dpos < (self.start as i64) || ((dpos as u64) > epos) { | |
808 | return Err(ByteIOError::WrongRange); | |
809 | } | |
810 | self.file.seek(SeekFrom::Start(dpos as u64)) | |
811 | } else { | |
812 | self.file.seek(pos) | |
813 | } | |
814 | }, | |
815 | }; | |
816 | match res { | |
817 | Ok(r) => Ok(r), | |
818 | Err(_) => Err(ByteIOError::SeekError), | |
819 | } | |
820 | } | |
821 | ||
822 | fn is_eof(&self) -> bool { | |
823 | self.eof | |
824 | } | |
825 | ||
826 | fn is_seekable(&mut self) -> bool { | |
827 | true | |
828 | } | |
829 | ||
830 | fn size(&mut self) -> i64 { | |
831 | -1 | |
832 | } | |
833 | ||
834 | fn flush(&mut self) -> ByteIOResult<()> { Ok(()) } | |
835 | } | |
836 | ||
837 | ||
28884194 KS |
838 | /// High-level bytestream writer. |
839 | /// | |
840 | /// User is supposed to create some writer implementing [`ByteIO`] trait e.g. [`MemoryWriter`] and use it to create `ByteWriter` which can be used for writing e.g. various integer types. | |
841 | /// | |
842 | /// # Examples | |
843 | /// | |
844 | /// ```` | |
845 | /// use nihav_core::io::byteio::{MemoryWriter,ByteWriter}; | |
846 | /// # use nihav_core::io::byteio::ByteIOResult; | |
847 | /// | |
848 | /// # fn foo() -> ByteIOResult<()> { | |
849 | /// let mut memory = [0u8; 4]; | |
850 | /// let mut mw = MemoryWriter::new_write(&mut memory); | |
851 | /// let mut bw = ByteWriter::new(&mut mw); | |
852 | /// let val = bw.write_u16be(42)?; // memory should be [ 0, 42, 0, 0 ] | |
853 | /// let val = bw.write_u16le(42)?; // memory should be [ 0, 42, 42, 0 ] | |
854 | /// # Ok(()) | |
855 | /// # } | |
856 | /// ```` | |
857 | /// | |
858 | /// [`ByteIO`]: ./trait.ByteIO.html | |
859 | /// [`MemoryWriter`]: ./struct.MemoryWriter.html | |
d532000c KS |
860 | #[allow(dead_code)] |
861 | pub struct ByteWriter<'a> { | |
ac818eac | 862 | io: &'a mut dyn ByteIO, |
d532000c KS |
863 | } |
864 | ||
28884194 | 865 | /// Bytestream writer to memory. |
d532000c KS |
866 | pub struct MemoryWriter<'a> { |
867 | buf: &'a mut [u8], | |
d532000c KS |
868 | pos: usize, |
869 | } | |
870 | ||
789354a8 KS |
871 | /// Bytestream writer to anything implementing `std::io::Write` and `std::io::Seek`. |
872 | pub struct FileWriter<T: Write+Seek> { | |
873 | file: Box<T>, | |
d532000c KS |
874 | } |
875 | ||
422e87e4 KS |
876 | /// Bytestream writer to memory. |
877 | /// | |
878 | /// Unlike [`MemoryWriter`] which writes to an array of fixed size, `GrowableMemoryWriter` grows output size when output size exceeds capacity. | |
879 | /// | |
880 | /// [`MemoryWriter`]: ./struct.MemoryWriter.html | |
881 | pub struct GrowableMemoryWriter<'a> { | |
882 | buf: &'a mut Vec<u8>, | |
883 | pos: usize, | |
884 | } | |
885 | ||
d532000c | 886 | impl<'a> ByteWriter<'a> { |
28884194 | 887 | /// Constructs a new instance of `ByteWriter`. |
ac818eac | 888 | pub fn new(io: &'a mut dyn ByteIO) -> Self { ByteWriter { io } } |
d532000c | 889 | |
28884194 | 890 | /// Writes byte array to the output. |
d532000c KS |
891 | pub fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { |
892 | self.io.write_buf(buf) | |
893 | } | |
894 | ||
28884194 | 895 | /// Writes single byte to the output. |
d532000c KS |
896 | pub fn write_byte(&mut self, val: u8) -> ByteIOResult<()> { |
897 | let buf: [u8; 1] = [val]; | |
898 | self.io.write_buf(&buf) | |
899 | } | |
900 | ||
28884194 | 901 | /// Writes 16-bit big-endian integer to the output. |
d532000c KS |
902 | pub fn write_u16be(&mut self, val: u16) -> ByteIOResult<()> { |
903 | let buf: [u8; 2] = [((val >> 8) & 0xFF) as u8, (val & 0xFF) as u8]; | |
904 | self.io.write_buf(&buf) | |
905 | } | |
906 | ||
28884194 | 907 | /// Writes 16-bit little-endian integer to the output. |
d532000c KS |
908 | pub fn write_u16le(&mut self, val: u16) -> ByteIOResult<()> { |
909 | let buf: [u8; 2] = [(val & 0xFF) as u8, ((val >> 8) & 0xFF) as u8]; | |
910 | self.io.write_buf(&buf) | |
911 | } | |
912 | ||
28884194 | 913 | /// Writes 24-bit big-endian integer to the output. |
d532000c KS |
914 | pub fn write_u24be(&mut self, val: u32) -> ByteIOResult<()> { |
915 | let buf: [u8; 3] = [((val >> 16) & 0xFF) as u8, ((val >> 8) & 0xFF) as u8, (val & 0xFF) as u8]; | |
916 | self.write_buf(&buf) | |
917 | } | |
918 | ||
28884194 | 919 | /// Writes 24-bit little-endian integer to the output. |
d532000c KS |
920 | pub fn write_u24le(&mut self, val: u32) -> ByteIOResult<()> { |
921 | let buf: [u8; 3] = [(val & 0xFF) as u8, ((val >> 8) & 0xFF) as u8, ((val >> 16) & 0xFF) as u8]; | |
922 | self.write_buf(&buf) | |
923 | } | |
924 | ||
28884194 | 925 | /// Writes 32-bit big-endian integer to the output. |
d532000c KS |
926 | pub fn write_u32be(&mut self, val: u32) -> ByteIOResult<()> { |
927 | self.write_u16be(((val >> 16) & 0xFFFF) as u16)?; | |
928 | self.write_u16be((val & 0xFFFF) as u16) | |
929 | } | |
930 | ||
28884194 | 931 | /// Writes 32-bit little-endian integer to the output. |
d532000c KS |
932 | pub fn write_u32le(&mut self, val: u32) -> ByteIOResult<()> { |
933 | self.write_u16le((val & 0xFFFF) as u16)?; | |
934 | self.write_u16le(((val >> 16) & 0xFFFF) as u16) | |
935 | } | |
936 | ||
28884194 | 937 | /// Writes 64-bit big-endian integer to the output. |
d532000c | 938 | pub fn write_u64be(&mut self, val: u64) -> ByteIOResult<()> { |
e243ceb4 KS |
939 | self.write_u32be((val >> 32) as u32)?; |
940 | self.write_u32be(val as u32) | |
d532000c KS |
941 | } |
942 | ||
28884194 | 943 | /// Writes 64-bit little-endian integer to the output. |
d532000c | 944 | pub fn write_u64le(&mut self, val: u64) -> ByteIOResult<()> { |
e243ceb4 KS |
945 | self.write_u32le(val as u32)?; |
946 | self.write_u32le((val >> 32) as u32) | |
d532000c KS |
947 | } |
948 | ||
28884194 | 949 | /// Writes 32-bit big-endian floating point number to the output. |
02a5bdaf KS |
950 | pub fn write_f32be(&mut self, val: f32) -> ByteIOResult<()> { |
951 | self.write_u32be(val.to_bits()) | |
952 | } | |
953 | ||
28884194 | 954 | /// Writes 32-bit little-endian floating point number to the output. |
02a5bdaf KS |
955 | pub fn write_f32le(&mut self, val: f32) -> ByteIOResult<()> { |
956 | self.write_u32le(val.to_bits()) | |
957 | } | |
958 | ||
28884194 | 959 | /// Writes 64-bit big-endian floating point number to the output. |
02a5bdaf KS |
960 | pub fn write_f64be(&mut self, val: f64) -> ByteIOResult<()> { |
961 | self.write_u64be(val.to_bits()) | |
962 | } | |
963 | ||
28884194 | 964 | /// Writes 64-bit little-endian floating point number to the output. |
02a5bdaf KS |
965 | pub fn write_f64le(&mut self, val: f64) -> ByteIOResult<()> { |
966 | self.write_u64le(val.to_bits()) | |
967 | } | |
968 | ||
28884194 | 969 | /// Reports the current write position. |
d532000c KS |
970 | pub fn tell(&mut self) -> u64 { |
971 | self.io.tell() | |
972 | } | |
973 | ||
28884194 | 974 | /// Seeks to the requested position. |
d532000c KS |
975 | pub fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { |
976 | self.io.seek(pos) | |
977 | } | |
978 | ||
28884194 | 979 | /// Reports the amount of bytes the writer can still write (-1 if unknown). |
d532000c KS |
980 | pub fn size_left(&mut self) -> i64 { |
981 | let sz = self.io.size(); | |
982 | if sz == -1 { return -1; } | |
983 | sz - (self.tell() as i64) | |
984 | } | |
cf095d56 KS |
985 | |
986 | /// Flushes output stream if possible. | |
987 | pub fn flush(&mut self) -> ByteIOResult<()> { | |
988 | self.io.flush() | |
989 | } | |
d532000c KS |
990 | } |
991 | ||
992 | impl<'a> MemoryWriter<'a> { | |
993 | ||
28884194 | 994 | /// Constructs a new instance of `MemoryWriter`. |
d532000c | 995 | pub fn new_write(buf: &'a mut [u8]) -> Self { |
1be85e00 | 996 | MemoryWriter { buf, pos: 0 } |
d532000c KS |
997 | } |
998 | ||
999 | fn real_seek(&mut self, pos: i64) -> ByteIOResult<u64> { | |
1be85e00 | 1000 | if pos < 0 || (pos as usize) > self.buf.len() { |
d532000c KS |
1001 | return Err(ByteIOError::WrongRange) |
1002 | } | |
1003 | self.pos = pos as usize; | |
1004 | Ok(pos as u64) | |
1005 | } | |
1006 | } | |
1007 | ||
1008 | impl<'a> ByteIO for MemoryWriter<'a> { | |
1009 | #[allow(unused_variables)] | |
1010 | fn read_byte(&mut self) -> ByteIOResult<u8> { | |
1011 | Err(ByteIOError::NotImplemented) | |
1012 | } | |
1013 | ||
1014 | #[allow(unused_variables)] | |
1015 | fn peek_byte(&mut self) -> ByteIOResult<u8> { | |
1016 | Err(ByteIOError::NotImplemented) | |
1017 | } | |
1018 | ||
1019 | #[allow(unused_variables)] | |
1020 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1021 | Err(ByteIOError::NotImplemented) | |
1022 | } | |
1023 | ||
1024 | #[allow(unused_variables)] | |
1025 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1026 | Err(ByteIOError::NotImplemented) | |
1027 | } | |
1028 | ||
1029 | #[allow(unused_variables)] | |
1030 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1031 | Err(ByteIOError::NotImplemented) | |
1032 | } | |
1033 | ||
1034 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { | |
1be85e00 | 1035 | if self.pos + buf.len() > self.buf.len() { return Err(ByteIOError::WriteError); } |
b36f412c | 1036 | self.buf[self.pos..][..buf.len()].copy_from_slice(buf); |
d532000c KS |
1037 | self.pos += buf.len(); |
1038 | Ok(()) | |
1039 | } | |
1040 | ||
1041 | fn tell(&mut self) -> u64 { | |
1042 | self.pos as u64 | |
1043 | } | |
1044 | ||
1045 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
422e87e4 KS |
1046 | let cur_pos = self.pos as i64; |
1047 | let cur_size = self.buf.len() as i64; | |
1048 | match pos { | |
1049 | SeekFrom::Start(x) => self.real_seek(x as i64), | |
1050 | SeekFrom::Current(x) => self.real_seek(cur_pos + x), | |
1051 | SeekFrom::End(x) => self.real_seek(cur_size + x), | |
1052 | } | |
1053 | } | |
1054 | ||
1055 | fn is_eof(&self) -> bool { | |
1056 | self.pos >= self.buf.len() | |
1057 | } | |
1058 | ||
1059 | fn is_seekable(&mut self) -> bool { | |
1060 | true | |
1061 | } | |
1062 | ||
1063 | fn size(&mut self) -> i64 { | |
1064 | self.buf.len() as i64 | |
1065 | } | |
cf095d56 KS |
1066 | |
1067 | fn flush(&mut self) -> ByteIOResult<()> { Ok(()) } | |
422e87e4 KS |
1068 | } |
1069 | ||
1070 | impl<'a> GrowableMemoryWriter<'a> { | |
1071 | ||
1072 | /// Constructs a new instance of `GrowableMemoryWriter`. | |
1073 | pub fn new_write(buf: &'a mut Vec<u8>) -> Self { | |
1074 | GrowableMemoryWriter { buf, pos: 0 } | |
1075 | } | |
1076 | ||
1077 | fn real_seek(&mut self, pos: i64) -> ByteIOResult<u64> { | |
1078 | if pos < 0 || (pos as usize) > self.buf.len() { | |
1079 | return Err(ByteIOError::WrongRange) | |
1080 | } | |
1081 | self.pos = pos as usize; | |
1082 | Ok(pos as u64) | |
1083 | } | |
1084 | } | |
1085 | ||
1086 | impl<'a> ByteIO for GrowableMemoryWriter<'a> { | |
1087 | #[allow(unused_variables)] | |
1088 | fn read_byte(&mut self) -> ByteIOResult<u8> { | |
1089 | Err(ByteIOError::NotImplemented) | |
1090 | } | |
1091 | ||
1092 | #[allow(unused_variables)] | |
1093 | fn peek_byte(&mut self) -> ByteIOResult<u8> { | |
1094 | Err(ByteIOError::NotImplemented) | |
1095 | } | |
1096 | ||
1097 | #[allow(unused_variables)] | |
1098 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1099 | Err(ByteIOError::NotImplemented) | |
1100 | } | |
1101 | ||
1102 | #[allow(unused_variables)] | |
1103 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1104 | Err(ByteIOError::NotImplemented) | |
1105 | } | |
1106 | ||
1107 | #[allow(unused_variables)] | |
1108 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1109 | Err(ByteIOError::NotImplemented) | |
1110 | } | |
1111 | ||
1112 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { | |
1113 | if self.pos + buf.len() > self.buf.len() { | |
1114 | self.buf.resize(self.pos + buf.len(), 0); | |
1115 | } | |
b36f412c | 1116 | self.buf[self.pos..][..buf.len()].copy_from_slice(buf); |
422e87e4 KS |
1117 | self.pos += buf.len(); |
1118 | Ok(()) | |
1119 | } | |
1120 | ||
1121 | fn tell(&mut self) -> u64 { | |
1122 | self.pos as u64 | |
1123 | } | |
1124 | ||
1125 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
1be85e00 KS |
1126 | let cur_pos = self.pos as i64; |
1127 | let cur_size = self.buf.len() as i64; | |
d532000c KS |
1128 | match pos { |
1129 | SeekFrom::Start(x) => self.real_seek(x as i64), | |
1130 | SeekFrom::Current(x) => self.real_seek(cur_pos + x), | |
1131 | SeekFrom::End(x) => self.real_seek(cur_size + x), | |
1132 | } | |
1133 | } | |
1134 | ||
e243ceb4 | 1135 | fn is_eof(&self) -> bool { |
1be85e00 | 1136 | self.pos >= self.buf.len() |
d532000c KS |
1137 | } |
1138 | ||
1139 | fn is_seekable(&mut self) -> bool { | |
1140 | true | |
1141 | } | |
1142 | ||
1143 | fn size(&mut self) -> i64 { | |
1144 | self.buf.len() as i64 | |
1145 | } | |
cf095d56 KS |
1146 | |
1147 | fn flush(&mut self) -> ByteIOResult<()> { Ok(()) } | |
d532000c KS |
1148 | } |
1149 | ||
789354a8 | 1150 | impl<T: Write+Seek> FileWriter<T> { |
28884194 | 1151 | /// Constructs a new instance of `FileWriter`. |
789354a8 KS |
1152 | pub fn new_write(file: T) -> Self { |
1153 | FileWriter { file: Box::new(file) } | |
d532000c KS |
1154 | } |
1155 | } | |
1156 | ||
789354a8 | 1157 | impl<T: Write+Seek> ByteIO for FileWriter<T> { |
d532000c KS |
1158 | #[allow(unused_variables)] |
1159 | fn read_byte(&mut self) -> ByteIOResult<u8> { | |
1160 | Err(ByteIOError::NotImplemented) | |
1161 | } | |
1162 | ||
1163 | #[allow(unused_variables)] | |
1164 | fn peek_byte(&mut self) -> ByteIOResult<u8> { | |
1165 | Err(ByteIOError::NotImplemented) | |
1166 | } | |
1167 | ||
1168 | #[allow(unused_variables)] | |
1169 | fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1170 | Err(ByteIOError::NotImplemented) | |
1171 | } | |
1172 | ||
1173 | #[allow(unused_variables)] | |
1174 | fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1175 | Err(ByteIOError::NotImplemented) | |
1176 | } | |
1177 | ||
1178 | #[allow(unused_variables)] | |
1179 | fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult<usize> { | |
1180 | Err(ByteIOError::NotImplemented) | |
1181 | } | |
1182 | ||
1183 | fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { | |
1184 | match self.file.write_all(buf) { | |
1185 | Ok(()) => Ok(()), | |
1186 | Err(_) => Err(ByteIOError::WriteError), | |
1187 | } | |
1188 | } | |
1189 | ||
1190 | fn tell(&mut self) -> u64 { | |
1191 | self.file.seek(SeekFrom::Current(0)).unwrap() | |
1192 | } | |
1193 | ||
1194 | fn seek(&mut self, pos: SeekFrom) -> ByteIOResult<u64> { | |
1195 | let res = self.file.seek(pos); | |
1196 | match res { | |
1197 | Ok(r) => Ok(r), | |
1198 | Err(_) => Err(ByteIOError::SeekError), | |
1199 | } | |
1200 | } | |
1201 | ||
e243ceb4 | 1202 | fn is_eof(&self) -> bool { |
d532000c KS |
1203 | false |
1204 | } | |
1205 | ||
1206 | fn is_seekable(&mut self) -> bool { | |
1207 | true | |
1208 | } | |
1209 | ||
1210 | fn size(&mut self) -> i64 { | |
1211 | -1 | |
1212 | } | |
cf095d56 KS |
1213 | |
1214 | fn flush(&mut self) -> ByteIOResult<()> { | |
1215 | match self.file.flush() { | |
1216 | Ok(()) => Ok(()), | |
1217 | Err(_) => Err(ByteIOError::WriteError), | |
1218 | } | |
1219 | } | |
90aa4e6b KS |
1220 | } |
1221 | ||
1222 | #[cfg(test)] | |
1223 | mod test { | |
1224 | use super::*; | |
1225 | use std::fs::File; | |
1226 | ||
1227 | #[test] | |
1228 | fn test_read() { | |
1229 | //const DATA : &'static [u8] = include_bytes!("../../assets/file"); | |
1230 | let buf: [u8; 64] = [1; 64]; | |
1231 | let mut mr = MemoryReader::new_read(&buf); | |
1232 | let mut reader = ByteReader::new(&mut mr); | |
1233 | assert_eq!(reader.read_byte().unwrap(), 0x01u8); | |
1234 | assert_eq!(reader.read_u16le().unwrap(), 0x0101u16); | |
1235 | assert_eq!(reader.read_u24le().unwrap(), 0x010101u32); | |
1236 | assert_eq!(reader.read_u32le().unwrap(), 0x01010101u32); | |
1237 | assert_eq!(reader.read_u64le().unwrap(), 0x0101010101010101u64); | |
1678d59a | 1238 | let mut file = File::open("assets/Misc/MaoMacha.asx").unwrap(); |
90aa4e6b KS |
1239 | let mut fr = FileReader::new_read(&mut file); |
1240 | let mut br2 = ByteReader::new(&mut fr); | |
1241 | assert_eq!(br2.read_byte().unwrap(), 0x30); | |
1242 | assert_eq!(br2.read_u24be().unwrap(), 0x26B275); | |
1243 | assert_eq!(br2.read_u24le().unwrap(), 0xCF668E); | |
1244 | assert_eq!(br2.read_u32be().unwrap(), 0x11A6D900); | |
1245 | assert_eq!(br2.read_u32le().unwrap(), 0xCE6200AA); | |
1246 | } | |
1247 | #[test] | |
1248 | fn test_write() { | |
d532000c KS |
1249 | let mut buf: [u8; 64] = [0; 64]; |
1250 | { | |
1251 | let mut mw = MemoryWriter::new_write(&mut buf); | |
1252 | let mut bw = ByteWriter::new(&mut mw); | |
1253 | bw.write_byte(0x00).unwrap(); | |
1254 | bw.write_u16be(0x0102).unwrap(); | |
1255 | bw.write_u24be(0x030405).unwrap(); | |
1256 | bw.write_u32be(0x06070809).unwrap(); | |
1257 | bw.write_u64be(0x0A0B0C0D0E0F1011).unwrap(); | |
1258 | bw.write_byte(0x00).unwrap(); | |
1259 | bw.write_u16le(0x0201).unwrap(); | |
1260 | bw.write_u24le(0x050403).unwrap(); | |
1261 | bw.write_u32le(0x09080706).unwrap(); | |
1262 | bw.write_u64le(0x11100F0E0D0C0B0A).unwrap(); | |
1263 | assert_eq!(bw.size_left(), 28); | |
1264 | } | |
1265 | for i in 0..0x12 { | |
1266 | assert_eq!(buf[(i + 0x00) as usize], i); | |
1267 | assert_eq!(buf[(i + 0x12) as usize], i); | |
1268 | } | |
90aa4e6b KS |
1269 | } |
1270 | } |