genio/
lib.rs

1//! This crate provides more generic alternatives to `std::io::*` traits and types. `std::io`
2//! suffers several issues because of over-use of `std::io::Error` type. One of them is allocation
3//! when creating `Error` type, other is inability to cleanly define errors which make sense in
4//! particular implementation, impossibility of use in `no_std` environments and more.
5//!
6//! To solve these problems, `genio::Read`, `genio::Write` and other traits are allowed to define
7//! their own error types. Together with other utilities and `std` glue they provide a way to write
8//! more clear, portable and re-usable code.
9
10#![no_std]
11#![deny(missing_docs)]
12
13#[cfg(feature = "std")]
14extern crate std;
15
16#[cfg(feature = "byteorder")]
17extern crate byteorder;
18
19extern crate void;
20
21#[cfg(feature = "std")]
22pub mod std_impls;
23
24pub mod error;
25pub mod ext;
26pub mod util;
27pub mod bufio;
28
29use void::Void;
30use error::{ReadExactError, ExtendError};
31use util::Chain;
32
33#[cfg(feature = "byteorder")]
34use byteorder::ByteOrder;
35
36/// The Read trait allows for reading bytes from a source.
37///
38/// Implementors of the Read trait are sometimes called 'readers'.
39///
40/// Readers are defined by one required method, `read()` and a required type `ReadError`. Each call
41/// to read will attempt to pull bytes from this source into a provided buffer. A number of other
42/// methods are implemented in terms of read(), giving implementors a number of ways to read bytes
43/// while only needing to implement a single method.
44///
45/// Readers are intended to be composable with one another. Many implementors throughout genio
46/// take and provide types which implement the Read trait.
47///
48/// Please note that each call to read may involve a system call, and therefore, using something
49/// that implements BufRead, such as BufReader, will be more efficient.
50pub trait Read {
51    /// Value of this type is returned when `read()` fails.
52    ///
53    /// It's highly recommended to use `Void` from `void` crate if `read()` can never fail.
54    type ReadError;
55
56    /// Pull some bytes from this source into the specified buffer, returning how many bytes were
57    /// read.
58    ///
59    /// This function does not provide any guarantees about whether it blocks waiting for data, but
60    /// if an object needs to block for a read but cannot it will typically signal this via an Err
61    /// return value.
62    ///
63    /// If the return value of this method is Ok(n), then it must be guaranteed that 0 <= n <=
64    /// buf.len(). A nonzero n value indicates that the buffer buf has been filled in with n bytes
65    /// of data from this source. If n is 0, then it can indicate one of two scenarios:
66    ///
67    /// 1. This reader has reached its "end of file" and will likely no longer be able to produce
68    ///    bytes. Note that this does not mean that the reader will always no longer be able to
69    ///    produce bytes.
70    ///
71    /// 2. The buffer specified was 0 bytes in length.
72    ///
73    /// No guarantees are provided about the contents of buf when this function is called,
74    /// implementations cannot rely on any property of the contents of buf being true. It is
75    /// recommended that implementations only write data to buf instead of reading its contents.
76    ///
77    /// # Errors
78    ///
79    /// If this function encounters any form of I/O or other error, an error
80    /// variant will be returned. If an error is returned then it must be
81    /// guaranteed that no bytes were read.
82    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::ReadError>;
83
84    /// Read the exact number of bytes required to fill `buf`.
85    ///
86    /// This function reads as many bytes as necessary to completely fill the specified buffer `buf`.
87    ///
88    /// No guarantees are provided about the contents of `buf` when this function is called,
89    /// implementations cannot rely on any property of the contents of `buf` being true. It is
90    /// recommended that implementations only write data to `buf` instead of reading its contents.
91    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<(), ReadExactError<Self::ReadError>> {
92        if self.available_bytes(buf.len()) {
93            while !buf.is_empty() {
94                let read_bytes = self.read(buf)?;
95                if read_bytes == 0 {
96                    return Err(ReadExactError::UnexpectedEnd);
97                }
98
99                let tmp = buf;
100                buf = &mut tmp[read_bytes..];
101            }
102            return Ok(());
103        } else {
104            Err(ReadExactError::UnexpectedEnd)
105        }
106    }
107
108    /// Hints whether there are at least `at_least` bytes available.
109    ///
110    /// This function should return true if it can't determine exact amount. That is also default.
111    ///
112    /// # Errors
113    ///
114    /// It is an error to return false even if there are more bytes available.
115    fn available_bytes(&self, _at_least: usize) -> bool {
116        true
117    }
118
119    /// Chains another reader after `self`. When self ends (returns Ok(0)), the other reader will
120    /// provide bytes to read.
121    fn chain<R: Read>(self, other: R) -> Chain<Self, R> where Self: Sized {
122        Chain::new(self, other)
123    }
124
125    /// Reads all bytes into any type that can be extended by a reader. This is more generic than
126    /// the case of `std::io` and might enable some optimizations.
127    ///
128    /// Of course, `std::Vec` impls `ExtendFromReader`.
129    fn read_to_end<T: ExtendFromReader>(&mut self, container: &mut T) -> Result<usize, ExtendError<Self::ReadError, T::ExtendError>> where Self: ReadOverwrite {
130        let mut total_bytes = 0;
131
132        loop {
133            let bytes = container.extend_from_reader(self)?;
134            if bytes == 0 {
135                return Ok(total_bytes)
136            }
137            total_bytes += bytes;
138        }
139    }
140
141    /// Creates a "by reference" adaptor for this instance of `Read`.
142    ///
143    /// The returned adaptor also implements `Read` and will simply borrow this current reader.
144    fn by_ref(&mut self) -> &mut Self where Self: Sized {
145        self
146    }
147
148    /// Reads an unsigned 16 bit integer from the underlying reader.
149    #[cfg(feature = "byteorder")]
150    fn read_u16<BO: ByteOrder>(&mut self) -> Result<u16, Self::WriteError> {
151        let mut buf = [0; 2];
152        self.read_exact(&mut buf)?;
153        Ok(BO::read_u16(&buf))
154    }
155
156    /// Reads an unsigned 32 bit integer from the underlying reader.
157    #[cfg(feature = "byteorder")]
158    fn read_u32<BO: ByteOrder>(&mut self) -> Result<u32, Self::WriteError> {
159        let mut buf = [0; 4];
160        self.read_exact(&mut buf)?;
161        Ok(BO::read_u32(&buf))
162    }
163
164    /// Reads an unsigned 64 bit integer from the underlying reader.
165    #[cfg(feature = "byteorder")]
166    fn read_u64<BO: ByteOrder>(&mut self) -> Result<u64, Self::WriteError> {
167        let mut buf = [0; 8];
168        self.read_exact(&mut buf)?;
169        Ok(BO::read_u64(&buf))
170    }
171
172    /// Reads an signed 16 bit integer from the underlying reader.
173    #[cfg(feature = "byteorder")]
174    fn read_i16<BO: ByteOrder>(&mut self) -> Result<i16, Self::WriteError> {
175        let mut buf = [0; 2];
176        self.read_exact(&mut buf)?;
177        Ok(BO::read_i16(&buf))
178    }
179
180    /// Reads an signed 32 bit integer from the underlying reader.
181    #[cfg(feature = "byteorder")]
182    fn read_i32<BO: ByteOrder>(&mut self) -> Result<i32, Self::WriteError> {
183        let mut buf = [0; 4];
184        self.read_exact(&mut buf)?;
185        Ok(BO::read_i32(&buf))
186    }
187
188    /// Reads an signed 64 bit integer from the underlying reader.
189    #[cfg(feature = "byteorder")]
190    fn read_i64<BO: ByteOrder>(&mut self) -> Result<i64, Self::WriteError> {
191        let mut buf = [0; 8];
192        self.read_exact(&mut buf)?;
193        Ok(BO::read_i64(&buf))
194    }
195
196    /// Reads a IEEE754 single-precision (4 bytes) floating point number from the underlying
197    /// reader.
198    #[cfg(feature = "byteorder")]
199    fn read_f32<BO: ByteOrder>(&mut self) -> Result<f32, Self::WriteError> {
200        let mut buf = [0; 4];
201        self.read_exact(&mut buf)?;
202        Ok(BO::read_f32(&buf))
203    }
204
205    /// Reads a IEEE754 double-precision (8 bytes) floating point number from the underlying
206    /// reader.
207    #[cfg(feature = "byteorder")]
208    fn read_f64<BO: ByteOrder>(&mut self) -> Result<f64, Self::WriteError> {
209        let mut buf = [0; 8];
210        self.read_exact(&mut buf)?;
211        Ok(BO::read_f64(&buf))
212    }
213}
214
215/// Some types can be extended by reading from reader. The most well-known is probably `Vec`. It
216/// is possible to implement it manually, but it may be more efficient if the type implements this
217/// trait directly. In case of `Vec`, it means reading directly into uninitialized part of reserved
218/// memory in case of the fast version of this trait.
219pub trait ExtendFromReaderSlow {
220    /// This type is returned when extending fails. For example, if not enough memory could be
221    /// allocated. All other errors should be passed directly from reader.
222    type ExtendError;
223
224    /// This method performs extending from reader - that means calling `read()` just once.
225    fn extend_from_reader_slow<R: Read + ?Sized>(&mut self, reader: &mut R) -> Result<usize, ExtendError<R::ReadError, Self::ExtendError>>;
226}
227
228/// This trait is similar to slow one. The difference is that thanks to reader guaranteeing
229/// correctness, this one can use uninitialized buffer.
230pub trait ExtendFromReader: ExtendFromReaderSlow {
231    /// This method performs extending from reader - that means calling `read()` just once.
232    fn extend_from_reader<R: Read + ReadOverwrite + ?Sized>(&mut self, reader: &mut R) -> Result<usize, ExtendError<R::ReadError, Self::ExtendError>>;
233}
234
235/// This marker trait declares that the Read trait is implemented correctly,
236/// that means:
237///
238/// 1. implementation of `read()` and `read_exact()` doesn't read from provided buffer.
239/// 2. if `read()` returns `Ok(n)`, then each of first `n` bytes was overwritten.
240/// 3. if `read_exact()` returns `Ok(())` then each byte of buffer was overwritten.
241///
242/// Breaking this should not cause huge problems since untrusted input should be checked anyway but
243/// it might leak internal state of the application, containing secret data like private keys.
244/// Think of the Hartbleed bug.
245pub unsafe trait ReadOverwrite: Read {}
246
247/// A trait for objects which are byte-oriented sinks.
248///
249/// Implementors of the `Write` trait are sometimes called 'writers'.
250///
251/// Writers are defined by two required types `WriteError`, `FlushError` and methods, `write()`
252/// and `flush()`:
253///
254/// The `write()` method will attempt to write some data into the object, returning how many
255/// bytes were successfully written.
256///
257/// The `flush()` method is useful for adaptors and explicit buffers themselves for ensuring that
258/// all buffered data has been pushed out to the 'true sink'.
259///
260/// Writers are intended to be composable with one another. Many implementors throughout
261/// `genio` take and provide types which implement the `Write` trait.
262pub trait Write {
263    /// Value of this type is returned when `write()` fails.
264    ///
265    /// It's highly recommended to use `Void` from `void` crate if `read()` can never fail.
266    type WriteError;
267
268    /// Value of this type is returned when `flush()` fails.
269    /// In case of low-level writers flush often does nothing and therefore doesn't return error,
270    /// so this type might be Void.
271    ///
272    /// It's highly recommended to use `Void` from `void` crate if `read()` can never fail.
273    type FlushError;
274
275    /// Write a buffer into this object, returning how many bytes were written.
276    ///
277    /// This function will attempt to write the entire contents of `buf`, but the entire write may
278    /// not succeed, or the write may also generate an error. A call to `write` represents *at most
279    /// one* attempt to write to any wrapped object.
280    ///
281    /// If the return value is `Ok(n)` then it must be guaranteed that `0 <= n <= buf.len()`. A return
282    /// value of `0` typically means that the underlying object is no longer able to accept bytes and
283    /// will likely not be able to in the future as well, or that the buffer provided is empty.
284    ///
285    /// # Errors
286    ///
287    /// Each call to write may generate an `WriteError` indicating that the operation could not be
288    /// completed. If an error is returned then no bytes in the buffer were written to this writer.
289    ///
290    /// It is **not** considered an error if the entire buffer could not be written to this writer.
291    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::WriteError>;
292
293    /// Flush this output stream, ensuring that all intermediately buffered contents reach their
294    /// destination.
295    ///
296    /// # Errors
297    ///
298    /// It is considered an error if not all bytes could be written due to I/O errors or EOF being
299    /// reached.
300    fn flush(&mut self) -> Result<(), Self::FlushError>;
301
302    /// Attempts to write an entire buffer into this `Write`.
303    fn write_all(&mut self, mut buf: &[u8]) -> Result<(), Self::WriteError> {
304        while !buf.is_empty() {
305            let len = self.write(buf)?;
306            buf = &buf[len..];
307        }
308        Ok(())
309    }
310
311    /// Hints the writer how much bytes will be written after call to this function.
312    /// If the maximum amount of bytes to be written is known then it should be passed as argument.
313    /// If the maximum amount is unknown, then minimum should be passed.
314    ///
315    /// Call to this function might enable some optimizations (e.g. pre-allocating buffer of
316    /// appropriate size). The implementors must not rely on this call to provide correct values or
317    /// on this function being called at all! (Especially they **must not** cause undefined
318    /// behavior.) However, performance might be arbitrarilly degraded in case caller provides
319    /// wrong value.
320    ///
321    /// The function is mandatory, as a lint to incentivize implementors to implement it, if
322    /// applicable. Note that if you implement this function, you must also implement
323    /// `uses_size_hint`.
324    fn size_hint(&mut self, bytes: usize);
325
326    /// Reports to the caller whether size hint is actually used. This can prevent costly
327    /// computation of size hint that would be thrown away.
328    fn uses_size_hint(&self) -> bool {
329        false
330    }
331
332    /// Writes an unsigned 16 bit integer to the underlying writer.
333    #[cfg(feature = "byteorder")]
334    fn write_u16<BO: ByteOrder>(&mut self, val: u16) -> Result<(), Self::WriteError> {
335        let mut buf = [0; 2];
336        BO::write_u16(&mut buf, val);
337        self.write_all(&buf)
338    }
339
340    /// Writes an unsigned 32 bit integer to the underlying writer.
341    #[cfg(feature = "byteorder")]
342    fn write_u32<BO: ByteOrder>(&mut self, val: u32) -> Result<(), Self::WriteError> {
343        let mut buf = [0; 4];
344        BO::write_u32(&mut buf, val);
345        self.write_all(&buf)
346    }
347
348    /// Writes an unsigned 64 bit integer to the underlying writer.
349    #[cfg(feature = "byteorder")]
350    fn write_u64<BO: ByteOrder>(&mut self, val: u64) -> Result<(), Self::WriteError> {
351        let mut buf = [0; 8];
352        BO::write_u64(&mut buf, val);
353        self.write_all(&buf)
354    }
355
356    /// Writes an unsigned n-bytes integer to the underlying writer.
357    ///
358    /// If the given integer is not representable in the given number of bytes, this method panics.
359    /// If nbytes > 8, this method panics.
360    #[cfg(feature = "byteorder")]
361    fn write_uint<BO: ByteOrder>(&mut self, val: u64, bytes: usize) -> Result<(), Self::WriteError> {
362        let mut buf = [0; 8];
363        BO::write_uint(&mut buf, val, bytes);
364        self.write_all(&buf)
365    }
366
367    /// Writes a signed 16 bit integer to the underlying writer.
368    #[cfg(feature = "byteorder")]
369    fn write_i16<BO: ByteOrder>(&mut self, val: i16) -> Result<(), Self::WriteError> {
370        let mut buf = [0; 2];
371        BO::write_i16(&mut buf, val);
372        self.write_all(&buf)
373    }
374
375    /// Writes a signed 32 bit integer to the underlying writer.
376    #[cfg(feature = "byteorder")]
377    fn write_i32<BO: ByteOrder>(&mut self, val: i32) -> Result<(), Self::WriteError> {
378        let mut buf = [0; 4];
379        BO::write_i32(&mut buf, val);
380        self.write_all(&buf)
381    }
382
383    /// Writes a signed 64 bit integer to the underlying writer.
384    #[cfg(feature = "byteorder")]
385    fn write_i64<BO: ByteOrder>(&mut self, val: i64) -> Result<(), Self::WriteError> {
386        let mut buf = [0; 8];
387        BO::write_i64(&mut buf, val);
388        self.write_all(&buf)
389    }
390
391    /// Writes a signed n-bytes integer to the underlying writer.
392    ///
393    /// If the given integer is not representable in the given number of bytes, this method panics.
394    /// If nbytes > 8, this method panics.
395    #[cfg(feature = "byteorder")]
396    fn write_int<BO: ByteOrder>(&mut self, val: i64, bytes: usize) -> Result<(), Self::WriteError> {
397        let mut buf = [0; 8];
398        BO::write_int(&mut buf, val, bytes);
399        self.write_all(&buf)
400    }
401
402    /// Writes a IEEE754 single-precision (4 bytes) floating point number to the underlying writer.
403    #[cfg(feature = "byteorder")]
404    fn write_f32<BO: ByteOrder>(&mut self, val: f32) -> Result<(), Self::WriteError> {
405        let mut buf = [0; 4];
406        BO::write_f32(&mut buf, val);
407        self.write_all(&buf)
408    }
409
410    /// Writes a IEEE754 double-precision (8 bytes) floating point number to the underlying writer.
411    #[cfg(feature = "byteorder")]
412    fn write_f64<BO: ByteOrder>(&mut self, val: f64) -> Result<(), Self::WriteError> {
413        let mut buf = [0; 4];
414        BO::write_f64(&mut buf, val);
415        self.write_all(&buf)
416    }
417}
418
419impl<'a, R: Read + ?Sized> Read for &'a mut R {
420    type ReadError = R::ReadError;
421
422    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::ReadError> {
423        (*self).read(buf)
424    }
425}
426
427impl<'a, W: Write + ?Sized> Write for &'a mut W {
428    type WriteError = W::WriteError;
429    type FlushError = W::FlushError;
430
431    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::WriteError> {
432        (*self).write(buf)
433    }
434
435    fn flush(&mut self) -> Result<(), Self::FlushError> {
436        (*self).flush()
437    }
438
439    fn size_hint(&mut self, bytes: usize) {
440        (*self).size_hint(bytes)
441    }
442
443    /// Reports to the caller whether size hint is actually used. This can prevent costly
444    /// computation of size hint that would be thrown away.
445    fn uses_size_hint(&self) -> bool {
446        (**self).uses_size_hint()
447    }
448}
449
450impl<'a> Read for &'a [u8] {
451    type ReadError = Void;
452
453    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::ReadError> {
454        use ::core::cmp::min;
455
456        let amt = min(buf.len(), self.len());
457        let (a, b) = self.split_at(amt);
458
459        // First check if the amount of bytes we want to read is small:
460        // `copy_from_slice` will generally expand to a call to `memcpy`, and
461        // for a single byte the overhead is significant.
462        if amt == 1 {
463            buf[0] = a[0];
464        } else {
465            buf[..amt].copy_from_slice(a);
466        }
467
468        *self = b;
469        Ok(amt)
470    }
471
472    fn available_bytes(&self, at_least: usize) -> bool {
473        self.len() >= at_least
474    }
475}
476
477impl<'a> Write for &'a mut [u8] {
478    type WriteError = error::BufferOverflow;
479    type FlushError = Void;
480
481    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::WriteError> {
482        if buf.len() <= self.len() {
483            let (first, second) = ::core::mem::replace(self, &mut []).split_at_mut(buf.len());
484            first.copy_from_slice(&buf[0..buf.len()]);
485            *self = second;
486            Ok(buf.len())
487        } else {
488            Err(error::BufferOverflow)
489        }
490    }
491
492    fn flush(&mut self) -> Result<(), Self::FlushError> {
493        Ok(())
494    }
495    
496    fn size_hint(&mut self, _bytes: usize) {}
497}