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