borsh/
nostd_io.rs

1//! Taken from https://github.com/bbqsrc/bare-io (with adjustments)
2
3use crate::__private::maybestd::string::String;
4use core::{convert::From, fmt, result};
5
6/// A specialized [`Result`] type for I/O operations.
7///
8/// This type is broadly used across [`std::io`] for any operation which may
9/// produce an error.
10///
11/// This typedef is generally used to avoid writing out [`io::Error`] directly and
12/// is otherwise a direct mapping to [`Result`].
13///
14/// While usual Rust style is to import types directly, aliases of [`Result`]
15/// often are not, to make it easier to distinguish between them. [`Result`] is
16/// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
17/// will generally use `io::Result` instead of shadowing the [prelude]'s import
18/// of [`std::result::Result`][`Result`].
19///
20/// [`std::io`]: crate::io
21/// [`io::Error`]: Error
22/// [`Result`]: crate::result::Result
23/// [prelude]: crate::prelude
24///
25/// # Examples
26///
27/// A convenience function that bubbles an `io::Result` to its caller:
28///
29/// ```
30/// use std::io;
31///
32/// fn get_string() -> io::Result<String> {
33///     let mut buffer = String::new();
34///
35///     io::stdin().read_line(&mut buffer)?;
36///
37///     Ok(buffer)
38/// }
39/// ```
40pub type Result<T> = result::Result<T, Error>;
41
42/// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
43/// associated traits.
44///
45/// Errors mostly originate from the underlying OS, but custom instances of
46/// `Error` can be created with crafted error messages and a particular value of
47/// [`ErrorKind`].
48///
49/// [`Read`]: crate::io::Read
50/// [`Write`]: crate::io::Write
51/// [`Seek`]: crate::io::Seek
52pub struct Error {
53    repr: Repr,
54}
55
56impl fmt::Debug for Error {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        fmt::Debug::fmt(&self.repr, f)
59    }
60}
61
62enum Repr {
63    Simple(ErrorKind),
64    Custom(Custom),
65}
66
67#[derive(Debug)]
68struct Custom {
69    kind: ErrorKind,
70    error: String,
71}
72
73/// A list specifying general categories of I/O error.
74///
75/// This list is intended to grow over time and it is not recommended to
76/// exhaustively match against it.
77///
78/// It is used with the [`io::Error`] type.
79///
80/// [`io::Error`]: Error
81#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
82// #[allow(deprecated)]
83#[non_exhaustive]
84pub enum ErrorKind {
85    /// An entity was not found, often a file.
86    NotFound,
87    /// The operation lacked the necessary privileges to complete.
88    PermissionDenied,
89    /// The connection was refused by the remote server.
90    ConnectionRefused,
91    /// The connection was reset by the remote server.
92    ConnectionReset,
93    /// The connection was aborted (terminated) by the remote server.
94    ConnectionAborted,
95    /// The network operation failed because it was not connected yet.
96    NotConnected,
97    /// A socket address could not be bound because the address is already in
98    /// use elsewhere.
99    AddrInUse,
100    /// A nonexistent interface was requested or the requested address was not
101    /// local.
102    AddrNotAvailable,
103    /// The operation failed because a pipe was closed.
104    BrokenPipe,
105    /// An entity already exists, often a file.
106    AlreadyExists,
107    /// The operation needs to block to complete, but the blocking operation was
108    /// requested to not occur.
109    WouldBlock,
110    /// A parameter was incorrect.
111    InvalidInput,
112    /// Data not valid for the operation were encountered.
113    ///
114    /// Unlike [`InvalidInput`], this typically means that the operation
115    /// parameters were valid, however the error was caused by malformed
116    /// input data.
117    ///
118    /// For example, a function that reads a file into a string will error with
119    /// `InvalidData` if the file's contents are not valid UTF-8.
120    ///
121    /// [`InvalidInput`]: ErrorKind::InvalidInput
122    InvalidData,
123    /// The I/O operation's timeout expired, causing it to be canceled.
124    TimedOut,
125    /// An error returned when an operation could not be completed because a
126    /// call to [`write`] returned [`Ok(0)`].
127    ///
128    /// This typically means that an operation could only succeed if it wrote a
129    /// particular number of bytes but only a smaller number of bytes could be
130    /// written.
131    ///
132    /// [`write`]: crate::io::Write::write
133    /// [`Ok(0)`]: Ok
134    WriteZero,
135    /// This operation was interrupted.
136    ///
137    /// Interrupted operations can typically be retried.
138    Interrupted,
139    /// Any I/O error not part of this list.
140    ///
141    /// Errors that are `Other` now may move to a different or a new
142    /// [`ErrorKind`] variant in the future. It is not recommended to match
143    /// an error against `Other` and to expect any additional characteristics,
144    /// e.g., a specific [`Error::raw_os_error`] return value.
145    Other,
146
147    /// An error returned when an operation could not be completed because an
148    /// "end of file" was reached prematurely.
149    ///
150    /// This typically means that an operation could only succeed if it read a
151    /// particular number of bytes but only a smaller number of bytes could be
152    /// read.
153    UnexpectedEof,
154
155    /// An operation could not be completed, because it failed
156    /// to allocate enough memory.
157    OutOfMemory,
158}
159
160impl ErrorKind {
161    pub(crate) fn as_str(&self) -> &'static str {
162        match *self {
163            ErrorKind::NotFound => "entity not found",
164            ErrorKind::PermissionDenied => "permission denied",
165            ErrorKind::ConnectionRefused => "connection refused",
166            ErrorKind::ConnectionReset => "connection reset",
167            ErrorKind::ConnectionAborted => "connection aborted",
168            ErrorKind::NotConnected => "not connected",
169            ErrorKind::AddrInUse => "address in use",
170            ErrorKind::AddrNotAvailable => "address not available",
171            ErrorKind::BrokenPipe => "broken pipe",
172            ErrorKind::AlreadyExists => "entity already exists",
173            ErrorKind::WouldBlock => "operation would block",
174            ErrorKind::InvalidInput => "invalid input parameter",
175            ErrorKind::InvalidData => "invalid data",
176            ErrorKind::TimedOut => "timed out",
177            ErrorKind::WriteZero => "write zero",
178            ErrorKind::Interrupted => "operation interrupted",
179            ErrorKind::Other => "other os error",
180            ErrorKind::UnexpectedEof => "unexpected end of file",
181            ErrorKind::OutOfMemory => "out of memory",
182        }
183    }
184}
185
186/// Intended for use for errors not exposed to the user, where allocating onto
187/// the heap (for normal construction via Error::new) is too costly.
188impl From<ErrorKind> for Error {
189    /// Converts an [`ErrorKind`] into an [`Error`].
190    ///
191    /// This conversion allocates a new error with a simple representation of error kind.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use std::io::{Error, ErrorKind};
197    ///
198    /// let not_found = ErrorKind::NotFound;
199    /// let error = Error::from(not_found);
200    /// assert_eq!("entity not found", format!("{}", error));
201    /// ```
202    #[inline]
203    fn from(kind: ErrorKind) -> Error {
204        Error {
205            repr: Repr::Simple(kind),
206        }
207    }
208}
209
210impl Error {
211    /// Creates a new I/O error from a known kind of error as well as an
212    /// arbitrary error payload.
213    ///
214    /// This function is used to generically create I/O errors which do not
215    /// originate from the OS itself. The `error` argument is an arbitrary
216    /// payload which will be contained in this [`Error`].
217    ///
218    /// Note that this function allocates memory on the heap.
219    /// If no extra payload is required, use the `From` conversion from
220    /// `ErrorKind`.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use std::io::{Error, ErrorKind};
226    ///
227    /// // errors can be created from strings
228    /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
229    ///
230    /// // errors can also be created from other errors
231    /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
232    ///
233    /// // creating an error without payload (and without memory allocation)
234    /// let eof_error = Error::from(ErrorKind::UnexpectedEof);
235    /// ```
236    #[inline(never)]
237    pub fn new<E>(kind: ErrorKind, error: E) -> Error
238    where
239        E: Into<String>,
240    {
241        Self::_new(kind, error.into())
242    }
243
244    /// Creates a new I/O error from an arbitrary error payload.
245    ///
246    /// This function is used to generically create I/O errors which do not
247    /// originate from the OS itself. It is a shortcut for [`Error::new`]
248    /// with [`ErrorKind::Other`].
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// use std::io::Error;
254    ///
255    /// // errors can be created from strings
256    /// let custom_error = Error::other("oh no!");
257    ///
258    /// // errors can also be created from other errors
259    /// let custom_error2 = Error::other(custom_error);
260    /// ```
261    pub fn other<E>(error: E) -> Error
262    where
263        E: Into<String>,
264    {
265        Self::_new(ErrorKind::Other, error.into())
266    }
267
268    fn _new(kind: ErrorKind, error: String) -> Error {
269        Error {
270            repr: Repr::Custom(Custom { kind, error }),
271        }
272    }
273
274    /// Returns a reference to the inner error wrapped by this error (if any).
275    ///
276    /// If this [`Error`] was constructed via [`new`] then this function will
277    /// return [`Some`], otherwise it will return [`None`].
278    ///
279    /// [`new`]: Error::new
280    ///
281    /// # Examples
282    ///
283    /// ```
284    /// use std::io::{Error, ErrorKind};
285    ///
286    /// fn print_error(err: &Error) {
287    ///     if let Some(inner_err) = err.get_ref() {
288    ///         println!("Inner error: {:?}", inner_err);
289    ///     } else {
290    ///         println!("No inner error");
291    ///     }
292    /// }
293    ///
294    /// fn main() {
295    ///     // Will print "No inner error".
296    ///     print_error(&Error::last_os_error());
297    ///     // Will print "Inner error: ...".
298    ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
299    /// }
300    /// ```
301    #[must_use]
302    #[inline]
303    pub fn get_ref(&self) -> Option<&str> {
304        match self.repr {
305            Repr::Simple(..) => None,
306            Repr::Custom(ref c) => Some(&c.error),
307        }
308    }
309
310    /// Consumes the `Error`, returning its inner error (if any).
311    ///
312    /// If this [`Error`] was constructed via [`new`] then this function will
313    /// return [`Some`], otherwise it will return [`None`].
314    ///
315    /// [`new`]: Error::new
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use std::io::{Error, ErrorKind};
321    ///
322    /// fn print_error(err: Error) {
323    ///     if let Some(inner_err) = err.into_inner() {
324    ///         println!("Inner error: {}", inner_err);
325    ///     } else {
326    ///         println!("No inner error");
327    ///     }
328    /// }
329    ///
330    /// fn main() {
331    ///     // Will print "No inner error".
332    ///     print_error(Error::last_os_error());
333    ///     // Will print "Inner error: ...".
334    ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
335    /// }
336    /// ```
337    #[must_use = "`self` will be dropped if the result is not used"]
338    #[inline]
339    pub fn into_inner(self) -> Option<String> {
340        match self.repr {
341            Repr::Simple(..) => None,
342            Repr::Custom(c) => Some(c.error),
343        }
344    }
345
346    /// Returns the corresponding [`ErrorKind`] for this error.
347    ///
348    /// # Examples
349    ///
350    /// ```
351    /// use std::io::{Error, ErrorKind};
352    ///
353    /// fn print_error(err: Error) {
354    ///     println!("{:?}", err.kind());
355    /// }
356    ///
357    /// fn main() {
358    ///     // Will print "Other".
359    ///     print_error(Error::last_os_error());
360    ///     // Will print "AddrInUse".
361    ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
362    /// }
363    /// ```
364    #[must_use]
365    #[inline]
366    pub fn kind(&self) -> ErrorKind {
367        match self.repr {
368            Repr::Custom(ref c) => c.kind,
369            Repr::Simple(kind) => kind,
370        }
371    }
372}
373
374impl fmt::Debug for Repr {
375    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
376        match *self {
377            Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
378            Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
379        }
380    }
381}
382
383impl fmt::Display for Error {
384    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
385        match self.repr {
386            Repr::Custom(ref c) => c.error.fmt(fmt),
387            Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
388        }
389    }
390}
391
392fn _assert_error_is_sync_send() {
393    fn _is_sync_send<T: Sync + Send>() {}
394    _is_sync_send::<Error>();
395}
396
397/// A trait for objects which are byte-oriented sinks.
398///
399/// Implementors of the `Write` trait are sometimes called 'writers'.
400///
401/// Writers are defined by two required methods, [`write`] and [`flush`]:
402///
403/// * The [`write`] method will attempt to write some data into the object,
404///   returning how many bytes were successfully written.
405///
406/// * The [`flush`] method is useful for adaptors and explicit buffers
407///   themselves for ensuring that all buffered data has been pushed out to the
408///   'true sink'.
409///
410/// Writers are intended to be composable with one another. Many implementors
411/// throughout [`std::io`] take and provide types which implement the `Write`
412/// trait.
413///
414/// [`write`]: Write::write
415/// [`flush`]: Write::flush
416/// [`std::io`]: self
417///
418/// # Examples
419///
420/// ```no_run
421/// use std::io::prelude::*;
422/// use std::fs::File;
423///
424/// fn main() -> std::io::Result<()> {
425///     let data = b"some bytes";
426///
427///     let mut pos = 0;
428///     let mut buffer = File::create("foo.txt")?;
429///
430///     while pos < data.len() {
431///         let bytes_written = buffer.write(&data[pos..])?;
432///         pos += bytes_written;
433///     }
434///     Ok(())
435/// }
436/// ```
437///
438/// The trait also provides convenience methods like [`write_all`], which calls
439/// `write` in a loop until its entire input has been written.
440///
441/// [`write_all`]: Write::write_all
442pub trait Write {
443    /// Write a buffer into this writer, returning how many bytes were written.
444    ///
445    /// This function will attempt to write the entire contents of `buf`, but
446    /// the entire write may not succeed, or the write may also generate an
447    /// error. A call to `write` represents *at most one* attempt to write to
448    /// any wrapped object.
449    ///
450    /// Calls to `write` are not guaranteed to block waiting for data to be
451    /// written, and a write which would otherwise block can be indicated through
452    /// an [`Err`] variant.
453    ///
454    /// If the return value is [`Ok(n)`] then it must be guaranteed that
455    /// `n <= buf.len()`. A return value of `0` typically means that the
456    /// underlying object is no longer able to accept bytes and will likely not
457    /// be able to in the future as well, or that the buffer provided is empty.
458    ///
459    /// # Errors
460    ///
461    /// Each call to `write` may generate an I/O error indicating that the
462    /// operation could not be completed. If an error is returned then no bytes
463    /// in the buffer were written to this writer.
464    ///
465    /// It is **not** considered an error if the entire buffer could not be
466    /// written to this writer.
467    ///
468    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
469    /// write operation should be retried if there is nothing else to do.
470    ///
471    /// # Examples
472    ///
473    /// ```no_run
474    /// use std::io::prelude::*;
475    /// use std::fs::File;
476    ///
477    /// fn main() -> std::io::Result<()> {
478    ///     let mut buffer = File::create("foo.txt")?;
479    ///
480    ///     // Writes some prefix of the byte string, not necessarily all of it.
481    ///     buffer.write(b"some bytes")?;
482    ///     Ok(())
483    /// }
484    /// ```
485    ///
486    /// [`Ok(n)`]: Ok
487    fn write(&mut self, buf: &[u8]) -> Result<usize>;
488
489    /// Flush this output stream, ensuring that all intermediately buffered
490    /// contents reach their destination.
491    ///
492    /// # Errors
493    ///
494    /// It is considered an error if not all bytes could be written due to
495    /// I/O errors or EOF being reached.
496    ///
497    /// # Examples
498    ///
499    /// ```no_run
500    /// use std::io::prelude::*;
501    /// use std::io::BufWriter;
502    /// use std::fs::File;
503    ///
504    /// fn main() -> std::io::Result<()> {
505    ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
506    ///
507    ///     buffer.write_all(b"some bytes")?;
508    ///     buffer.flush()?;
509    ///     Ok(())
510    /// }
511    /// ```
512    fn flush(&mut self) -> Result<()>;
513
514    /// Attempts to write an entire buffer into this writer.
515    ///
516    /// This method will continuously call [`write`] until there is no more data
517    /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
518    /// returned. This method will not return until the entire buffer has been
519    /// successfully written or such an error occurs. The first error that is
520    /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
521    /// returned.
522    ///
523    /// If the buffer contains no data, this will never call [`write`].
524    ///
525    /// # Errors
526    ///
527    /// This function will return the first error of
528    /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
529    ///
530    /// [`write`]: Write::write
531    ///
532    /// # Examples
533    ///
534    /// ```no_run
535    /// use std::io::prelude::*;
536    /// use std::fs::File;
537    ///
538    /// fn main() -> std::io::Result<()> {
539    ///     let mut buffer = File::create("foo.txt")?;
540    ///
541    ///     buffer.write_all(b"some bytes")?;
542    ///     Ok(())
543    /// }
544    /// ```
545    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
546        while !buf.is_empty() {
547            match self.write(buf) {
548                Ok(0) => {
549                    return Err(Error::new(
550                        ErrorKind::WriteZero,
551                        "failed to write whole buffer",
552                    ));
553                }
554                Ok(n) => buf = &buf[n..],
555                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
556                Err(e) => return Err(e),
557            }
558        }
559        Ok(())
560    }
561    /// Writes a formatted string into this writer, returning any error
562    /// encountered.
563    ///
564    /// This method is primarily used to interface with the
565    /// [`format_args!()`] macro, but it is rare that this should
566    /// explicitly be called. The [`write!()`] macro should be favored to
567    /// invoke this method instead.
568    ///
569    /// This function internally uses the [`write_all`] method on
570    /// this trait and hence will continuously write data so long as no errors
571    /// are received. This also means that partial writes are not indicated in
572    /// this signature.
573    ///
574    /// [`write_all`]: Write::write_all
575    ///
576    /// # Errors
577    ///
578    /// This function will return any I/O error reported while formatting.
579    ///
580    /// # Examples
581    ///
582    /// ```no_run
583    /// use std::io::prelude::*;
584    /// use std::fs::File;
585    ///
586    /// fn main() -> std::io::Result<()> {
587    ///     let mut buffer = File::create("foo.txt")?;
588    ///
589    ///     // this call
590    ///     write!(buffer, "{:.*}", 2, 1.234567)?;
591    ///     // turns into this:
592    ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
593    ///     Ok(())
594    /// }
595    /// ```
596    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
597        // Create a shim which translates a Write to a fmt::Write and saves
598        // off I/O errors. instead of discarding them
599        struct Adaptor<'a, T: ?Sized + 'a> {
600            inner: &'a mut T,
601            error: Result<()>,
602        }
603
604        impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
605            fn write_str(&mut self, s: &str) -> fmt::Result {
606                match self.inner.write_all(s.as_bytes()) {
607                    Ok(()) => Ok(()),
608                    Err(e) => {
609                        self.error = Err(e);
610                        Err(fmt::Error)
611                    }
612                }
613            }
614        }
615
616        let mut output = Adaptor {
617            inner: self,
618            error: Ok(()),
619        };
620        match fmt::write(&mut output, fmt) {
621            Ok(()) => Ok(()),
622            Err(..) => {
623                // check if the error came from the underlying `Write` or not
624                if output.error.is_err() {
625                    output.error
626                } else {
627                    Err(Error::new(ErrorKind::Other, "formatter error"))
628                }
629            }
630        }
631    }
632
633    /// Creates a "by reference" adaptor for this instance of `Write`.
634    ///
635    /// The returned adaptor also implements `Write` and will simply borrow this
636    /// current writer.
637    ///
638    /// # Examples
639    ///
640    /// ```no_run
641    /// use std::io::Write;
642    /// use std::fs::File;
643    ///
644    /// fn main() -> std::io::Result<()> {
645    ///     let mut buffer = File::create("foo.txt")?;
646    ///
647    ///     let reference = buffer.by_ref();
648    ///
649    ///     // we can use reference just like our original buffer
650    ///     reference.write_all(b"some bytes")?;
651    ///     Ok(())
652    /// }
653    /// ```
654    fn by_ref(&mut self) -> &mut Self
655    where
656        Self: Sized,
657    {
658        self
659    }
660}
661
662impl<W: Write + ?Sized> Write for &mut W {
663    #[inline]
664    fn write(&mut self, buf: &[u8]) -> Result<usize> {
665        (**self).write(buf)
666    }
667
668    #[inline]
669    fn flush(&mut self) -> Result<()> {
670        (**self).flush()
671    }
672
673    #[inline]
674    fn write_all(&mut self, buf: &[u8]) -> Result<()> {
675        (**self).write_all(buf)
676    }
677
678    #[inline]
679    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
680        (**self).write_fmt(fmt)
681    }
682}
683
684/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
685/// its data.
686///
687/// Note that writing updates the slice to point to the yet unwritten part.
688/// The slice will be empty when it has been completely overwritten.
689impl Write for &mut [u8] {
690    #[inline]
691    fn write(&mut self, data: &[u8]) -> Result<usize> {
692        let amt = core::cmp::min(data.len(), self.len());
693        let (a, b) = core::mem::replace(self, &mut []).split_at_mut(amt);
694        a.copy_from_slice(&data[..amt]);
695        *self = b;
696        Ok(amt)
697    }
698
699    #[inline]
700    fn write_all(&mut self, data: &[u8]) -> Result<()> {
701        if self.write(data)? == data.len() {
702            Ok(())
703        } else {
704            Err(Error::new(
705                ErrorKind::WriteZero,
706                "failed to write whole buffer",
707            ))
708        }
709    }
710
711    #[inline]
712    fn flush(&mut self) -> Result<()> {
713        Ok(())
714    }
715}
716
717/// Write is implemented for `Vec<u8>` by appending to the vector.
718/// The vector will grow as needed.
719impl Write for alloc::vec::Vec<u8> {
720    #[inline]
721    fn write(&mut self, buf: &[u8]) -> Result<usize> {
722        self.extend_from_slice(buf);
723        Ok(buf.len())
724    }
725
726    #[inline]
727    fn write_all(&mut self, buf: &[u8]) -> Result<()> {
728        self.extend_from_slice(buf);
729        Ok(())
730    }
731
732    #[inline]
733    fn flush(&mut self) -> Result<()> {
734        Ok(())
735    }
736}
737
738/// The `Read` trait allows for reading bytes from a source.
739///
740/// Implementors of the `Read` trait are called 'readers'.
741///
742/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
743/// will attempt to pull bytes from this source into a provided buffer. A
744/// number of other methods are implemented in terms of [`read()`], giving
745/// implementors a number of ways to read bytes while only needing to implement
746/// a single method.
747///
748/// Readers are intended to be composable with one another. Many implementors
749/// throughout [`std::io`] take and provide types which implement the `Read`
750/// trait.
751///
752/// Please note that each call to [`read()`] may involve a system call, and
753/// therefore, using something that implements [`BufRead`], such as
754/// [`BufReader`], will be more efficient.
755///
756/// # Examples
757///
758/// [`File`]s implement `Read`:
759///
760/// ```no_run
761/// use std::io;
762/// use std::io::prelude::*;
763/// use std::fs::File;
764///
765/// fn main() -> io::Result<()> {
766///     let mut f = File::open("foo.txt")?;
767///     let mut buffer = [0; 10];
768///
769///     // read up to 10 bytes
770///     f.read(&mut buffer)?;
771///
772///     let mut buffer = Vec::new();
773///     // read the whole file
774///     f.read_to_end(&mut buffer)?;
775///
776///     // read into a String, so that you don't need to do the conversion.
777///     let mut buffer = String::new();
778///     f.read_to_string(&mut buffer)?;
779///
780///     // and more! See the other methods for more details.
781///     Ok(())
782/// }
783/// ```
784///
785/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
786///
787/// ```no_run
788/// # use std::io;
789/// use std::io::prelude::*;
790///
791/// fn main() -> io::Result<()> {
792///     let mut b = "This string will be read".as_bytes();
793///     let mut buffer = [0; 10];
794///
795///     // read up to 10 bytes
796///     b.read(&mut buffer)?;
797///
798///     // etc... it works exactly as a File does!
799///     Ok(())
800/// }
801/// ```
802///
803/// [`read()`]: Read::read
804/// [`&str`]: prim@str
805/// [`std::io`]: self
806/// [`File`]: crate::fs::File
807pub trait Read {
808    /// Pull some bytes from this source into the specified buffer, returning
809    /// how many bytes were read.
810    ///
811    /// This function does not provide any guarantees about whether it blocks
812    /// waiting for data, but if an object needs to block for a read and cannot,
813    /// it will typically signal this via an [`Err`] return value.
814    ///
815    /// If the return value of this method is [`Ok(n)`], then implementations must
816    /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
817    /// that the buffer `buf` has been filled in with `n` bytes of data from this
818    /// source. If `n` is `0`, then it can indicate one of two scenarios:
819    ///
820    /// 1. This reader has reached its "end of file" and will likely no longer
821    ///    be able to produce bytes. Note that this does not mean that the
822    ///    reader will *always* no longer be able to produce bytes. As an example,
823    ///    on Linux, this method will call the `recv` syscall for a [`TcpStream`],
824    ///    where returning zero indicates the connection was shut down correctly. While
825    ///    for [`File`], it is possible to reach the end of file and get zero as result,
826    ///    but if more data is appended to the file, future calls to `read` will return
827    ///    more data.
828    /// 2. The buffer specified was 0 bytes in length.
829    ///
830    /// It is not an error if the returned value `n` is smaller than the buffer size,
831    /// even when the reader is not at the end of the stream yet.
832    /// This may happen for example because fewer bytes are actually available right now
833    /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
834    ///
835    /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
836    /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
837    /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
838    /// `n > buf.len()`.
839    ///
840    /// No guarantees are provided about the contents of `buf` when this
841    /// function is called, implementations cannot rely on any property of the
842    /// contents of `buf` being true. It is recommended that *implementations*
843    /// only write data to `buf` instead of reading its contents.
844    ///
845    /// Correspondingly, however, *callers* of this method must not assume any guarantees
846    /// about how the implementation uses `buf`. The trait is safe to implement,
847    /// so it is possible that the code that's supposed to write to the buffer might also read
848    /// from it. It is your responsibility to make sure that `buf` is initialized
849    /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
850    /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
851    ///
852    /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
853    ///
854    /// # Errors
855    ///
856    /// If this function encounters any form of I/O or other error, an error
857    /// variant will be returned. If an error is returned then it must be
858    /// guaranteed that no bytes were read.
859    ///
860    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
861    /// operation should be retried if there is nothing else to do.
862    ///
863    /// # Examples
864    ///
865    /// [`File`]s implement `Read`:
866    ///
867    /// [`Ok(n)`]: Ok
868    /// [`File`]: crate::fs::File
869    /// [`TcpStream`]: crate::net::TcpStream
870    ///
871    /// ```no_run
872    /// use std::io;
873    /// use std::io::prelude::*;
874    /// use std::fs::File;
875    ///
876    /// fn main() -> io::Result<()> {
877    ///     let mut f = File::open("foo.txt")?;
878    ///     let mut buffer = [0; 10];
879    ///
880    ///     // read up to 10 bytes
881    ///     let n = f.read(&mut buffer[..])?;
882    ///
883    ///     println!("The bytes: {:?}", &buffer[..n]);
884    ///     Ok(())
885    /// }
886    /// ```
887    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
888
889    /// Read the exact number of bytes required to fill `buf`.
890    ///
891    /// This function reads as many bytes as necessary to completely fill the
892    /// specified buffer `buf`.
893    ///
894    /// No guarantees are provided about the contents of `buf` when this
895    /// function is called, implementations cannot rely on any property of the
896    /// contents of `buf` being true. It is recommended that implementations
897    /// only write data to `buf` instead of reading its contents. The
898    /// documentation on [`read`] has a more detailed explanation on this
899    /// subject.
900    ///
901    /// # Errors
902    ///
903    /// If this function encounters an error of the kind
904    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
905    /// will continue.
906    ///
907    /// If this function encounters an "end of file" before completely filling
908    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
909    /// The contents of `buf` are unspecified in this case.
910    ///
911    /// If any other read error is encountered then this function immediately
912    /// returns. The contents of `buf` are unspecified in this case.
913    ///
914    /// If this function returns an error, it is unspecified how many bytes it
915    /// has read, but it will never read more than would be necessary to
916    /// completely fill the buffer.
917    ///
918    /// # Examples
919    ///
920    /// [`File`]s implement `Read`:
921    ///
922    /// [`read`]: Read::read
923    /// [`File`]: crate::fs::File
924    ///
925    /// ```no_run
926    /// use std::io;
927    /// use std::io::prelude::*;
928    /// use std::fs::File;
929    ///
930    /// fn main() -> io::Result<()> {
931    ///     let mut f = File::open("foo.txt")?;
932    ///     let mut buffer = [0; 10];
933    ///
934    ///     // read exactly 10 bytes
935    ///     f.read_exact(&mut buffer)?;
936    ///     Ok(())
937    /// }
938    /// ```
939    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
940        default_read_exact(self, buf)
941    }
942
943    /// Creates a "by reference" adaptor for this instance of `Read`.
944    ///
945    /// The returned adapter also implements `Read` and will simply borrow this
946    /// current reader.
947    ///
948    /// # Examples
949    ///
950    /// [`File`]s implement `Read`:
951    ///
952    /// [`File`]: crate::fs::File
953    ///
954    /// ```no_run
955    /// use std::io;
956    /// use std::io::Read;
957    /// use std::fs::File;
958    ///
959    /// fn main() -> io::Result<()> {
960    ///     let mut f = File::open("foo.txt")?;
961    ///     let mut buffer = Vec::new();
962    ///     let mut other_buffer = Vec::new();
963    ///
964    ///     {
965    ///         let reference = f.by_ref();
966    ///
967    ///         // read at most 5 bytes
968    ///         reference.take(5).read_to_end(&mut buffer)?;
969    ///
970    ///     } // drop our &mut reference so we can use f again
971    ///
972    ///     // original file still usable, read the rest
973    ///     f.read_to_end(&mut other_buffer)?;
974    ///     Ok(())
975    /// }
976    /// ```
977    fn by_ref(&mut self) -> &mut Self
978    where
979        Self: Sized,
980    {
981        self
982    }
983}
984
985fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
986    while !buf.is_empty() {
987        match this.read(buf) {
988            Ok(0) => break,
989            Ok(n) => {
990                let tmp = buf;
991                buf = &mut tmp[n..];
992            }
993            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
994            Err(e) => return Err(e),
995        }
996    }
997    if !buf.is_empty() {
998        Err(Error::new(
999            ErrorKind::UnexpectedEof,
1000            "failed to fill whole buffer",
1001        ))
1002    } else {
1003        Ok(())
1004    }
1005}
1006
1007impl<R: Read + ?Sized> Read for &mut R {
1008    #[inline]
1009    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1010        (**self).read(buf)
1011    }
1012
1013    #[inline]
1014    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
1015        (**self).read_exact(buf)
1016    }
1017}
1018
1019impl Read for &[u8] {
1020    #[inline]
1021    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1022        let amt = core::cmp::min(buf.len(), self.len());
1023        let (a, b) = self.split_at(amt);
1024
1025        // First check if the amount of bytes we want to read is small:
1026        // `copy_from_slice` will generally expand to a call to `memcpy`, and
1027        // for a single byte the overhead is significant.
1028        if amt == 1 {
1029            buf[0] = a[0];
1030        } else {
1031            buf[..amt].copy_from_slice(a);
1032        }
1033
1034        *self = b;
1035        Ok(amt)
1036    }
1037
1038    #[inline]
1039    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
1040        if buf.len() > self.len() {
1041            return Err(Error::new(
1042                ErrorKind::UnexpectedEof,
1043                "failed to fill whole buffer",
1044            ));
1045        }
1046        let (a, b) = self.split_at(buf.len());
1047
1048        // First check if the amount of bytes we want to read is small:
1049        // `copy_from_slice` will generally expand to a call to `memcpy`, and
1050        // for a single byte the overhead is significant.
1051        if buf.len() == 1 {
1052            buf[0] = a[0];
1053        } else {
1054            buf.copy_from_slice(a);
1055        }
1056
1057        *self = b;
1058        Ok(())
1059    }
1060}