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