|
| 1 | +//! This primarily tests that `impl Debug for str` is correct for a number of inputs, |
| 2 | +//! but also that it minimizes calls to the underlying `Write`r. |
| 3 | +//! While that is an implementation detail and there are no guarantees about it, |
| 4 | +//! we should still try to minimize those calls over time rather than regress them. |
| 5 | +//! |
| 6 | +//! See also the benchmarks in `core/benches/str/debug.rs`. |
| 7 | +use std::fmt::{self, Write}; |
| 8 | + |
| 9 | +#[derive(Default)] |
| 10 | +struct CountingWriter { |
| 11 | + buf: String, |
| 12 | + write_calls: usize, |
| 13 | +} |
| 14 | + |
| 15 | +impl Write for CountingWriter { |
| 16 | + fn write_str(&mut self, s: &str) -> fmt::Result { |
| 17 | + self.buf.push_str(s); |
| 18 | + self.write_calls += 1; |
| 19 | + Ok(()) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +fn run_fmt(s: &str, expected: &str, expected_write_calls: usize) { |
| 24 | + let mut w = CountingWriter::default(); |
| 25 | + |
| 26 | + write!(&mut w, "{s:?}").unwrap(); |
| 27 | + assert_eq!(s.len(), 64); |
| 28 | + assert_eq!(w.buf, expected); |
| 29 | + assert_eq!(w.write_calls, expected_write_calls); |
| 30 | +} |
| 31 | + |
| 32 | +#[test] |
| 33 | +fn ascii_only() { |
| 34 | + run_fmt( |
| 35 | + "just a bit of ascii text that has no escapes. 64 bytes exactly!!", |
| 36 | + r#""just a bit of ascii text that has no escapes. 64 bytes exactly!!""#, |
| 37 | + 3, |
| 38 | + ); |
| 39 | +} |
| 40 | + |
| 41 | +#[test] |
| 42 | +fn ascii_escapes() { |
| 43 | + run_fmt( |
| 44 | + "some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte", |
| 45 | + r#""some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte""#, |
| 46 | + 21, |
| 47 | + ); |
| 48 | +} |
| 49 | + |
| 50 | +#[test] |
| 51 | +fn some_unicode() { |
| 52 | + run_fmt( |
| 53 | + "egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.", |
| 54 | + r#""egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.""#, |
| 55 | + 3, |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +#[test] |
| 60 | +fn mostly_unicode() { |
| 61 | + run_fmt("предложение из кириллических букв.", r#""предложение из кириллических букв.""#, 3); |
| 62 | +} |
| 63 | + |
| 64 | +#[test] |
| 65 | +fn mixed() { |
| 66 | + run_fmt( |
| 67 | + "\"❤️\"\n\"hűha ez betű\"\n\"кириллических букв\".", |
| 68 | + r#""\"❤\u{fe0f}\"\n\"hűha ez betű\"\n\"кириллических букв\".""#, |
| 69 | + 36, |
| 70 | + ); |
| 71 | +} |
0 commit comments