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