]> git.lizzy.rs Git - rust.git/blob - src/test/ui/write-fmt-errors.rs
Rollup merge of #62469 - czipperz:liballoc-add-doc-links, r=GuillaumeGomez
[rust.git] / src / test / ui / write-fmt-errors.rs
1 // run-pass
2
3 use std::fmt;
4 use std::io::{self, Error, Write, sink};
5
6 struct ErrorDisplay;
7
8 impl fmt::Display for ErrorDisplay {
9     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
10         Err(fmt::Error)
11     }
12 }
13
14 struct ErrorWriter;
15
16 const FORMAT_ERROR: io::ErrorKind = io::ErrorKind::Other;
17 const WRITER_ERROR: io::ErrorKind = io::ErrorKind::NotConnected;
18
19 impl Write for ErrorWriter {
20     fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
21         Err(Error::new(WRITER_ERROR, "not connected"))
22     }
23
24     fn flush(&mut self) -> io::Result<()> { Ok(()) }
25 }
26
27 fn main() {
28     // Test that the error from the formatter is propagated.
29     let res = write!(sink(), "{} {} {}", 1, ErrorDisplay, "bar");
30     assert!(res.is_err(), "formatter error did not propagate");
31     assert_eq!(res.unwrap_err().kind(), FORMAT_ERROR);
32
33     // Test that an underlying error is propagated
34     let res = write!(ErrorWriter, "abc");
35     assert!(res.is_err(), "writer error did not propagate");
36
37     // Writer error
38     let res = write!(ErrorWriter, "abc {}", ErrorDisplay);
39     assert!(res.is_err(), "writer error did not propagate");
40     assert_eq!(res.unwrap_err().kind(), WRITER_ERROR);
41
42     // Formatter error
43     let res = write!(ErrorWriter, "{} abc", ErrorDisplay);
44     assert!(res.is_err(), "formatter error did not propagate");
45     assert_eq!(res.unwrap_err().kind(), FORMAT_ERROR);
46 }